Malcr001
Malcr001

Reputation: 8289

Remove array items larger than .. number

I have an array. I would like to remove any items that surpass the third item leaving 'a', 'b', and 'c' in the array. How do I do this?

//my array
var array_name = ['a', 'b', 'c', 'd', 'e'];

//Number of array items to remove
var remove_array_items = 3;

//Desired result
var array_name = ['a', 'b', 'c'];

Upvotes: 2

Views: 144

Answers (2)

user2437417
user2437417

Reputation:

Truncate the Array by simply setting its .length to a lower number.

array_name.length = 3;

DEMO: http://jsfiddle.net/hX29y/

Upvotes: 3

techfoobar
techfoobar

Reputation: 66693

You can simply do:

array_name.splice(remove_array_items);

to remove all elements on or after the one at index: remove_array_items


var array_name = ['a', 'b', 'c', 'd', 'e'];
var remove_array_items = 3;

// note this **modifies** the array it is called on
array_name.splice(remove_array_items);

// array_name is now ["a", "b", "c"]

Upvotes: 4

Related Questions