How to Get Values From Array With Specific Range in Javascript

Ruby World 💎

In Ruby, I can get the specific range from an array like this;

>> myArray = ['a','b','c','d','e','f','g', 'h', 'i']
>> myArray[0..4]
=> ['a','b','c', 'd', 'e']

However, since I am not using Ruby on this project and am using vanilla Javascript, I wonder how to achieve the same result.

Turns out that it's extremely easy to do !!!

Javascript World 🌈

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

Easy right.

If you notice, the last index is different from the Ruby implementation.

This is because the last index is non-inclusive; to mimic ruby's behavior you have to increment the end value.

So, in Ruby;

myArray[m..n]

in Javascript;

myArray.slice(m, n+1);

the second argument to slice in Ruby is the length, but in JavaScript it is the index of the last element.

Other stuff

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

var myArray = ['a','b','c','d','e','f','g', 'h','i'];
var lastThree = myArray.slice(-3);  //g, h, i

2) If end is omitted, slice extracts through the end of the sequence (arr.length).

var myArray = ['a','b','c','d','e','f','g', 'h','i'];
var noEndInSlice = myArray.slice(5);  //f, g, h, i

which indicate that the end value is optional

The End

Resources:
1 2 3

16