Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array: get "range" of items

Is there an equivalent for ruby's array[n..m] in JavaScript?

For example:

>> a = ['a','b','c','d','e','f','g'] >> a[0..2] => ['a','b','c'] 
like image 903
shdev Avatar asked Aug 26 '10 23:08

shdev


People also ask

Which method in JavaScript return a range of elements of an array?

slice() method returns the selected elements in an array, as a new array object.

How do you slice an array of objects in JavaScript?

slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.


2 Answers

Use the array.slice(begin [, end]) function.

var a = ['a','b','c','d','e','f','g']; var sliced = a.slice(0, 3); //will contain ['a', 'b', 'c'] 

The last index is non-inclusive; to mimic ruby's behavior you have to increment the end value. So I guess slice behaves more like a[m...n] in ruby.

like image 139
Vivin Paliath Avatar answered Oct 14 '22 12:10

Vivin Paliath


The second argument in slice is optional, too:

var fruits = ['apple','banana','peach','plum','pear']; var slice1 = fruits.slice(1, 3);  //banana, peach var slice2 = fruits.slice(3);  //plum, pear 

You can also pass a negative number, which selects from the end of the array:

var slice3 = fruits.slice(-3);  //peach, plum, pear 

Here's the W3 Schools reference link.

like image 23
David Hoerster Avatar answered Oct 14 '22 12:10

David Hoerster