Is it possible to remove the contents of the array based on the index? If I have 2 arrays like these:
Array1 that contains 15 values and I want to get the last 10 va
To keep the first ten items:
if (theArray.length > 10) theArray = theArray.slice(0, 10);
or, perhaps less intuitive:
if (theArray.length > 10) theArray.length = 10;
To keep the last ten items:
if (theArray.length > 10) theArray = theArray.slice(theArray.length - 10, 10);
You can use a negative value for the first parameter to specify length - n, and omitting the second parameter gets all items to the end, so the same can also be written as:
if (theArray.length > 10) theArray = theArray.slice(-10);
The splice
method is used to remove items and replace with other items, but if you specify no new items it can be used to only remove items. To keep the first ten items:
if (theArray.length > 10) theArray.splice(10, theArray.length - 10);
To keep the last ten items:
if (theArray.length > 10) theArray.splice(0, theArray.length - 10);
Use the function array.splice(index, count)
to remove count
elements at index
. To remove elements from the end, use array1.splice(array1.length - 10, 1);
See splice()
The
splice()
method changes the content of an array by removing existing elements and/or adding new elements.
It won't create a new array, if you want to create new array use slice
.
Kind of hard to follow your question, but try these:
array = array.slice(-10);
// or
last10 = array.splice(-10);
// array has first array.length-10 elements