Categories
JavaScript Answers

How to get a range of items from a JavaScript array?

Spread the love

Sometimes, we want to get a range of items from a JavaScript array.

In this article, we’ll look at how to get a range of items from a JavaScript array.

How to get a range of items from a JavaScript array?

To get a range of items from a JavaScript array, we can use the array slice method.

For instance, we write

const fruits = ["apple", "banana", "peach", "plum", "pear"];
const slice1 = fruits.slice(1, 3);
const slice2 = fruits.slice(3);

to call fruits.slice with 1 and 3 to return an array from fruits at index 1 and 2.

Next, we call slice with 3 to return an array from fruits at index 3 to the end of the array.

Therefore, slice1 is ['banana', 'peach'].

And slice2 is ['plum', 'pear'].

Conclusion

To get a range of items from a JavaScript array, we can use the array slice method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *