Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

Thanks

share|improve this question
3  
yes, coffeescript! New-and-improved range, slice, splice and loop syntax. – Lance Pollard May 18 '11 at 23:02
add comment (requires an account with 50 reputation)

4 Answers

up vote 27 down vote accepted

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.

share|improve this answer
add comment (requires an account with 50 reputation)

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

share|improve this answer
actually it would be a.slice(0, 3). slice in JavaScript doesn't included the end index. – Anurag Aug 26 '10 at 23:15
D'oh, nice catch, updated. – Robert Aug 26 '10 at 23:25
add comment (requires an account with 50 reputation)

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);
share|improve this answer
add comment (requires an account with 50 reputation)

The second argument in slice is optional, too:

var fruits = ['apple','banana','peach','plum','pear'];
var slice1 = fruits.slice(1, 3);  //banana, peach, plum
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.

share|improve this answer
3  
How about linking to Mozilla's javascript reference, which is far more informative and much better written than the W3 schools site (which has nothing to do with the W3C)? developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… – Bobby Jack Aug 26 '10 at 23:50
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.