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 values.
Before removing elements:
array1 == [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
After removing elements:
array1 == [5,6,7,8,9,10,11,12,13,14]
Array2 that contains 15 values and then I want to get only the first 10 values.
Before removing elements:
array2 == [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
After removing elements:
array2 == [0,1,2,3,4,5,6,7,8,9]
But there are conditions that must be fulfilled:
if the array only contains 3 elements is not necessary to discard the elements in the array, as well as if the array contains 10 elements only. but if the array contains more than 10 elements, the excess is discarded.
Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.
You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.
The splice() function adds or removes an item from an array using the index. To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With