Skip to content Skip to sidebar Skip to footer

Remove All Elements After A Position In An Array Of Objects In Javascript Using Splice

I am wondering if there is an easy way to splice out all elements after a key position. array.splice(index,howmany,item1,.....,itemX) The docs say the 2nd element that specifies t

Solution 1:

I am wondering if there is an easy way to splice out all elements after a key position in a json array.

If it's all elements after a key position, you do this:

array.length = theKeyPosition;

E.g.:

vararray = [
    "one",
    "two",
    "three",
    "four",
    "five",
    "six"
];
var theKeyPosition = 3;
array.length = theKeyPosition; // Remove all elements starting with "four"

If you don't yet know the key position, in an ES5 environment (and this can be shimmed), you use filter:

vararray = [
    "one",
    "two",
    "three",
    "four",
    "five",
    "six"
];
var keep = true;
array = array.filter(function(entry) {
    if (entry === "four") {
        keep = false;
    }
    return keep;
});

That's using strings, but you can easily change if (entry === "four") { to if (entry.someProperty === someValue) { for your array of objects.

Solution 2:

The second argument is actually optional for Array.prototype.splice() and the desired behaviour can be achieved using only the first argument.

For example (copied form the accepted answer):

const array = [
    "one",
    "two",
    "three",
    "four",
    "five",
    "six"
];
const theKeyPosition = 3;
array.splice(theKeyPosition+1); // Remove all elements starting with "four"console.log(array);

However, I still prefer setting the length property as it's supposed to be faster (I can't find the JSPerf result, please help me here).

Read more about this on MDN or on my other answer to a similar question.

Solution 3:

Try this method, which remove all objects in array

array.splice(0, array.length);

Post a Comment for "Remove All Elements After A Position In An Array Of Objects In Javascript Using Splice"