How to get the first N elements of an Array in JavaScript


In this blog you will understand how to get the first N javascript array elements, common errors, and a fun coding problem to sharpen your skills.


Ways to access first n elements of javascript array

The slice() Method: My Preferred Choice to get first N elements of JS array

The slice() method is a versatile and non-destructive way to handle arrays.

  • Returns a new array without altering the original.
  • If the end index exceeds the array length, it safely returns up to the end of the array.
JavaScript
let fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
let firstThree = fruits.slice(0, 3);

console.log(firstThree); // ['Apple', 'Banana', 'Cherry']

The splice() Method: Handle with Care

splice(), while similar in name to slice(), modifies the original array, which can be a source of confusion.

JavaScript
let fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
let removed = fruits.splice(0, 3);

console.log(removed); // ['Apple', 'Banana', 'Cherry']
console.log(fruits); // Remaining elements: ['Date', 'Elderberry']

Destructuring Arrays to get first N elements of array in js

Destructuring offers a concise way to extract multiple elements based on their position.

  • Order is preserved in destructuring; it starts from the first element (index 0) and moves right.
  • This method is ideal when you know the fixed number of elements to extract.
JavaScript
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
let [first, second, third] = fruits;

console.log(first, second, third); // Apple Banana Cherry

Using a for loop to get first N elements of js array

A traditional for loop gives you control over the number of iterations. If we need to element wise operation, or checks then we can use this familiar approach. But requires manual handling of array bounds, and can cause Index out of bounds (undefined elements returned from array) if not careful.

JavaScript
let fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
let firstThree = [];
for (let i = 0; i < 3; i++) {
  firstThree.push(fruits[i]);
}

console.log(firstThree); // ['Apple', 'Banana', 'Cherry']

Using filter() to get first N elements of js array

We can use Array.filter() method with filter condition on each element in the array. But:

  • filter() iterates over the entire array, even if we need a need a small part of the array.
  • This becomes inefficient for large arrays.
JavaScript
const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

const n = 2;

const first2 = fruits.filter((element, index) => index < n);
console.log(first2); // 👉️ ['Apple', 'Banana']

Using Lodash’s take() to get first N elements

If you are already using Lodash library in your project, then can use take() function. It returns a new array and does not modify the original one.

JavaScript
let _ = require('lodash');
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

let firstTwo = _.take(fruits, 2);

console.log(firstTwo); // ['Apple', 'Banana']

Tips when accessing first few elements of javascript array

  • Using splice() instead of slice(): As shown, splice() modifies the original array, which can lead to unexpected results.
  • Index Out of Bounds: If we access array element at position greater than the array’s length, then you get undefined. To avoid surprises, always ensure you are within array’s length, while accessing array elements.

🧪Practice Coding Problem: Programmer’s Bookshelf

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

As a programmer, you have a long list of books to read. Write a function to select the first N books from your list.

JavaScript
/**
 * Returns the first N elements of an array.
 * 
 * @param {Array} array - An array of book titles.
 * @param {number} n - Number of titles to return.
 * @return {Array} An array containing the first N book titles.
 */
function selectBooks(array, n) {
  // > > > 👉 Write code here 👈 < < <
}

// Driver code:
let books = ['JavaScript: The Good Parts', 'Eloquent JavaScript', 'You Don't Know JS', 'JavaScript & JQuery', 'Learn JavaScript Visually'];
console.log(selectBooks(books, 3)); // ['JavaScript: The Good Parts', 'Eloquent JavaScript', 'You Don't Know JS']
Please attempt before seeing the Answer:
JavaScript
function selectBooks(array, n) {
  return array.slice(0, n);
}

Explanation:

  • It doesn’t modify the original array, ensuring that our list of books remains intact.
  • It can handle scenarios where n is greater than the array’s length by returning the entire array.

Hopefully, this blogpost gave you several approaches to access first few elements of Javascript array. Keep coding! 🚀👨‍💻

Scroll to Top