JavaScript Array: get "range" of items

JavascriptRubyArraysRange

Javascript Problem Overview


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']

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

a.slice(0, 3) Would be the equivalent of your function in your example.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice

Solution 4 - Javascript

Ruby and Javascript both have a slice method, but watch out that the second argument to slice in Ruby is the length, but in JavaScript it is the index of the last element:

var shortArray = array.slice(start, end);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshdevView Question on Stackoverflow
Solution 1 - JavascriptVivin PaliathView Answer on Stackoverflow
Solution 2 - JavascriptDavid HoersterView Answer on Stackoverflow
Solution 3 - JavascriptRobertView Answer on Stackoverflow
Solution 4 - JavascriptDouglasView Answer on Stackoverflow