I have an array: aNumeros=[1, 5, 6, 7, 8, 9, 10, 12];
I want to create another array from that, which contains the last 5 numbers:
aNuevo= [7, 8, 9, 10, 12]
thanks in advance
I have an array: aNumeros=[1, 5, 6, 7, 8, 9, 10, 12];
I want to create another array from that, which contains the last 5 numbers:
aNuevo= [7, 8, 9, 10, 12]
thanks in advance
You can do it using the splice function, passing as a parameter the position from where you want to cut.
let aNumeros=[1, 5, 6, 7, 8, 9, 10, 12];
let aNuevo = aNumeros.slice(aNumeros.length-5)
console.log(aNuevo)
In this case, as the starting position, we pass the length of the array (aNumeros) and subtract 5, so we will always look for the last 5.
Note: If there is no end position, it will leave a new array with the elements from the start position and until the end.
Take a look at the documentation, to see how it works in more detail link
In order to respond to your concern I share the following code segment, I hope you find it useful, greetings:
<script>
// uso del evento ready de jQuery para generar el example requerido
$(function() {
// arreglo inicial (en orden aleatorio)
var aNumeros=[1, 6, 5, 8, 7, 9, 12, 10];
// impresion de arreglo inicial
console.log("aNumeros: " + aNumeros.toString());
// arreglo ordenado usando function nativas de js
var arrOrdenado = aNumeros.sort(function(a, b){return a - b});
// impresion de arr ordenado
console.log("arrOrdenado: " + arrOrdenado.toString());
// uso de la function slice luego del ordenamiento para cortar
var aNuevo = arrOrdenado.slice(arrOrdenado.length-5)
// impresion del arr que requieres...
console.log("aNuevo: " + aNuevo.toString());
// fin de function ready de jQuery
});
// fin de segmento de javascript
</script>