I have an array:
array = ['mario','luigi','kong']
I call its splice function to remove all items before an index:
array.splice(1) //-> ['luigi','kong']
I'm just wondering if there is a function similar to splice to remove all items after an index:
pseudo code
array.mirrorsplice(1) //-> ['mario','luigi']
Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.
Use Array.length
to set a new size for an array, which is faster than Array.splice
to mutate:
var array = ['mario','luigi','kong', 1, 3, 6, 8]; array.length=2; alert(array); // shows "mario,luigi";
Why is it faster? Because .splice
has to create a new array containing all the removed items, whereas .length
creates nothing and "returns" a number instead of a new array.
To address .splice
usage, you can feed it a negative index, along with a huge number to chop off the end of an array:
var array = ['mario','luigi','kong']; array.splice(-1, 9e9); alert(array); // shows "mario,luigi";
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