1

I am curious to know how I can quickly and most efficiently remove a number of items from an array in JavaScript without creating a loop.

EXAMPLE:

var array = [1,2,3,4,5,6,7,8,9];
array.remove[0..4]; //pseudo code

console.log(array);//result would then be [6,7,8,9]

Is there a function for this, or is a custom loop required? Rudimentary question I suppose, but just wondering out of curiosity.

1
  • you can get a subset of an array in javascript with slice Commented Aug 15, 2014 at 20:14

3 Answers 3

4

Use Array#splice:

var array = [1,2,3,4,5,6,7,8,9];
array.splice(0, 4); // returns [1,2,3,4]
console.log(array); // logs [5,6,7,8,9]
Sign up to request clarification or add additional context in comments.

Comments

0

You could just use .slice() on the array.

var array = [1,2,3,4,5,6,7,8,9];
array = array.slice(5,array.length);

3 Comments

[].slice() never removes items from an array, it creates a new array.
And then assigning it to the original object array in effect removes the items.
Good point - a nice solution, although it does create a new array. Thanks Bradley!
0

Using filter method

var a = [1,2,3,4,5,6,7,8,9], b = [];
b = a.filter(function(element, index){ return index > 4 });

Output of b[]

[6,7,8,9]

1 Comment

[].filter never removes items from an array, thankfully.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.