105

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']
Starkers
  • 10,273
  • 21
  • 95
  • 158
  • 1
    Possible duplicate of [Remove all elements after a position in an array of objects in Javascript using splice](https://stackoverflow.com/questions/24862347/remove-all-elements-after-a-position-in-an-array-of-objects-in-javascript-using) – Krisztián Balla Feb 20 '18 at 11:05

6 Answers6

202

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";
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
dandavis
  • 16,370
  • 5
  • 40
  • 36
  • 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. http://stackoverflow.com/questions/31547315/is-it-an-antipattern-to-set-an-array-length-in-javascript/31560542#31560542 – Daniel F Jan 20 '17 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 :) – James Harrington Mar 01 '21 at 04: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 '21 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 '21 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 '22 at 02:10
  • @mattsoave: setting a new and longer length won't actually add any new values to an array, it will just update the length property. Consider: `let r=[1];r.length=5;Object.values(r);//==[1]` – dandavis Dec 14 '22 at 04:22
  • @dandavis True. You could maybe get into trouble with something like `for (let i = 0; i < arr.length; i++) { ... }`, but you should probably be avoiding that in other ways already (e.g. `arr.forEach()`). – mattsoave Dec 14 '22 at 20:39
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.
sha-1
  • 1,954
  • 2
  • 17
  • 23
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.

0xC0DED00D
  • 19,522
  • 20
  • 117
  • 184
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"];
Yagnesh Khamar
  • 184
  • 3
  • 8
  • 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. – Yagnesh Khamar May 08 '20 at 13:00
  • should be the correct answer imo – Gabe M Jul 05 '23 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)

Collin
  • 394
  • 5
  • 14