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
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']
// get first 10 elements of an array in JavaScript
array.slice(0, 10);
// ['get', 'first', 'n', 'elements', 'of', 'an', 'array'];
array.slice(0,1); // ['get']
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 the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.