Reputation: 33
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.
Upvotes: 1
Views: 180
Reputation: 9235
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]
Upvotes: 0
Reputation: 39
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);
Upvotes: 0
Reputation: 32598
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]
Upvotes: 4