107

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']
1

6 Answers 6

207

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";
7
  • 13
    Could reducing length cause a memory leak or does the javascript engine handle this? --- Ok, according to the ECMAScript specs this is clearly defined and handled correctly, the elements will get deleted. stackoverflow.com/questions/31547315/…
    – Daniel F
    Jan 20, 2017 at 14:53
  • 5
    Pro tip you can use array.splice(0, Infinity). I mean i would be hard pressed to believe you could have an array with more than 9000000000 items in it... But you do feel cool when you have a reason to use the Infinity keyword in JS :) Mar 1, 2021 at 4:12
  • Would the array.length trick work for say.... getting only 6,8 in the sample array? Because I don't see how you can get the last elements in an array using the length trick. That should only work with splice correct?
    – Hangfish
    May 18, 2021 at 16:18
  • @Hangfish: if you only want to get elements and not mutate the array, use .slice(-2). If you need to collect elements you remove, use .splice()
    – dandavis
    May 18, 2021 at 16:31
  • 1
    If you are using this to trim an array to a max length and if you're not certain your array is longer than the max, you probably will want to check first: const maxLen = 3; if (array.length > maxLen) array.length = maxLen; Otherwise you will end up adding empty values to an array that is already short enough.
    – mattsoave
    Dec 14, 2022 at 2:10
21

Though assigning a shorter value to the array length(as @dandavis said) is the fastest and simplest way to remove trailing element from an array, you can also do that using a similar method like splice which is known as slice. Like following:

array = ['mario', 'luigi', 'kong'];

array = array.slice(0, 2); //Need to assign it to the same or another variable

console.log(array); //["mario", "luigi"]

As you can see you need to store the returned value from slice method. To understand 'why', here are the major distinction between slice and splice method:

  • The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
  • The splice() method changes the original array and slice() method doesn’t change the original array.
2
10

To remove all items after an index:

var array = ['mario','luigi','kong'],
index = 1; // your index here
array = array.splice(index + 1, array.length - (index + 1) );
// 3 - (1+1) = 1
// 1 is the remaining number of element(s) in array
// hence, splice 1 after index

Result:

['mario', 'luigi']

You need to +1 since splice starts removing at the index.

5

I think you misunderstood the usage of Array.prototype.splice(). It already does what you asked for (remove everything after an index, read below paragraph for correction) and it does return the deleted values. I think you got confused with the returned value as the current value of the array.

Array.prototype.splice() however, removes the provided index value too, which is basically equivalent of setting the length of the array. So if you call it as array.splice(2), it'll set the length to 2 and everything including the values at index 2 and after will be deleted. This is provided that the current length of the array is greater than the first parameter provided to Array.prototype.splice().

For example:

const array = ['mario','luigi','kong'];
const deletedItem = array.splice(1);
console.log(array); // ['mario']
console.log(deletedItem); // ['luigi','kong']

For more information: refer to the MDN doc.

1
  • However, I'd still prefer the array.length modification, as splice can be confusing at times.
    – 0xC0DED00D
    Jun 11, 2020 at 4:10
3

You can use splice. Here is a demo.

var array = ['mario','luigi','kong']

To remove all the elements after an index:

var removedElement = array.splice(index, array.length)

removedElement will have the list of elements removed from the array.

example:

let index = 2;
var removedElement = array.splice(2, array.length); 
removedElement = ["kong"];
array = ["mario", "luigi"];
2
  • don't know the reason for downvoting, but this function is been used in some of my live projects and is working fine for any sort of dynamic lengths. But always welcome changes for betterment. May 8, 2020 at 13:00
  • should be the correct answer imo
    – Gabe M
    Jul 5, 2023 at 21:30
1

You can use .slice to accomplish this.

Example (removes all but the first 1000 entries from the array):

originalArray = originalArray.slice(0, 1000)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.