DEV Community

Amirul Asyraf
Amirul Asyraf

Posted on

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']
Enter fullscreen mode Exit fullscreen mode

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 🌈

You can use array.slice(begin [, end]) !!!

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

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]
Enter fullscreen mode Exit fullscreen mode

in Javascript;

myArray.slice(m, n+1);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

which indicate that the end value is optional

The End


Resources:
1 2 3

Top comments (0)