Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all items after an index

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'] 
like image 798
Starkers Avatar asked Oct 26 '14 00:10

Starkers


People also ask

How do I remove an item from an array index?

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.


1 Answers

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"; 
like image 129
dandavis Avatar answered Sep 25 '22 21:09

dandavis