How to get first N elements of an array in JavaScript

#javascript #array

Last updated on Jun 7, 2021 by Suraj Sharma



In this tutorial, you will learn two ways to get the first N elements of an array in JavaScript


1.Using Array.slice


The Array.slice method returns elements of an array into a new array. It accepts two arguments; start and end

Pass the 0 as the first argument and n as the last argument to get the first n elements of an array.

const array = ['get', 'first', 'n', 'elements', 'of', 'an', 'array'];

array.slice(0, 3);
// ['get','first', 'n']

array.slice(0, 10);
// ['get', 'first', 'n', 'elements', 'of', 'an', 'array'];

array.slice(0,1);
// ['get']


2. Using Array.filter


The Array.filter method can also be used to get the first n elements of an array into a new array.

Check if element’s index is less than N inside the callback function

const array = ['get', 'first', 'n', 'elements', 'of', 'an', 'array'];

const n = 3;

array.filter((a, index)=> index<3);
// ['get', 'first', 'n']


Related Solutions


Rate this post


Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.