How to get first N elements of an array in Javascript

Javascript get first N elements from an Array example; In this tutorial you will learn how to get the first N elements from an Array in javascript;

In javascript (Js) we can use the arr.slice() and array.filter() method to get the first elements from the array.

Example 1: Using Array.slice

The Array.slice method returns elements of an array into a new array. It accepts two arguments; start and end; Here bellow we pass the 0 as the first argument and n (2) as the last argument to get the first n elements of an array.

const arr = ['h', 'e', 'l', 'l', 'o'];

const first2 = arr.slice(0, 2); // ['h', 'l']
console.log(first2);

const first3 = arr.slice(0, 3); // ['h', 'e', 'l']
console.log(first3);

Example 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. In below example we check if element’s index is less than N (3) inside the callback function.

const arr = ['h', 'e', 'l', 'l', 'o'];

const n = 3;

let result =  arr.filter((a, index)=> index < n);
console.log(result) // ['h', 'e']

I hope these examples help you to get the first N elements from array in javascript.