Explain Codes LogoExplain Codes Logo

How to get first N number of elements from an array

javascript
slice
filter
immutability
Anton ShumikhinbyAnton Shumikhin·Aug 11, 2024
TLDR

To get the first N elements from an array arr in JavaScript, use the slice method like so: arr.slice(0, N). This returns a new array with the desired elements.

let firstTwoElements = [1, 2, 3, 4, 5].slice(0, 2); // Output: [1, 2], faster than instant noodles!

Slice: Jack of all trades

In JavaScript, the slice() method is simplicity meets power. Wielding this , you can easily create a sub-array from the original one, without the need for more convoluted methods like map() or reduce(). The best part? Slice() does not mutate the original array, making it a solid choice for adhering to immutability principles, which modern programming paradigms and libraries (like React) highly recommend.

Direct array modification: Chop, chop!

There might be times when you'd want to modify the original array to get your first N elements. In such cases you can truncate it by directly modifying its length property:

let arr = [1, 2, 3, 4, 5]; arr.length = 2; console.log(arr); // arr is now [1, 2], chopping off the array. Samurai Style!

This technique is quick, but remember, use it judiciously as it permanently modifies the original array.

Filter: The crafty picker

If you're seeking more control on picking elements based on conditions other than their position, filter() is your ally. Have a look:

let firstTwoElements = [1, 2, 3, 4, 5].filter((item, index) => index < 2); // Output: [1, 2]

Remember, filter() journeys through the entire array, which, while fetching you the first N elements, is a tad less efficient than our good old slice().

Immutability in modern frameworks

Frameworks such as React champion the cause of immutability. So slice() becomes even more relevant, as it leaves the original array untouched. Here's how you can utilise it when creating a list in React:

let firstNElements = data.slice(0, N); let listItems = firstNElements.map((item) => <li key={item.id}>{item.value}</li>); // Who let the dogs out? React did. Unique key required for each li!

Note the need for a unique key attribute with each list element - hands off, it's React's reconciliation process working to optimise rendering!

Code readability hits high note

Even the simplest of code must be readable and maintainable. Storing the desired size of your array in a well-named variable can improve both:

const podiumFinishers = 3; // Doing our bit for the readability relay race let firstThreeElements = arr.slice(0, podiumFinishers);