Clue Mediator

Get the first N number of elements from an array in JavaScript

📅January 5, 2021

Today we’ll show you how to get the first N number of elements from an array in JavaScript. There are multiple ways to get N number of items from an array using JavaScript.

You may check the few more articles related to the Array.

Ways to get the first N number of elements from an array

  1. slice() method
  2. filter() method

1. slice() method

In this method, we will use the slice() method to get the first 5 items from an array. It is a very simple method to get the first 5 elements from the list. It's the most preferable method to get items.

Example 1: Get the first 5 elements

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// get the first 5 elements
const n = 5;

const newArr = arr.splice(0, n);
console.log(newArr);
// [1, 2, 3, 4, 5]

Example 2: Get the first 2 elements

const arr = [
  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
  },
  {
    userId: 2,
    id: 2,
    title: "quis ut nam facilis et officia qui",
    completed: false
  },
  {
    userId: 1,
    id: 3,
    title: "fugiat veniam minus",
    completed: false
  }
];

const n = 2;

const newArr = arr.splice(0, n);
console.log(newArr);
/*
[
  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
  },
  {
    userId: 2,
    id: 2,
    title: "quis ut nam facilis et officia qui",
    completed: false
  }
]
*/

2. filter() method

Using the filter() method, we can also get the first N number of elements from the list. Here we need to use the index of elements to filter the records.

Example 1: Get the first 5 elements

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// get the first 5 elements
const n = 5;

const newArr = arr.filter((x, i) => i < n);
console.log(newArr);
// [1, 2, 3, 4, 5]

Example 2: Get the first 2 elements

const arr = [
  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
  },
  {
    userId: 2,
    id: 2,
    title: "quis ut nam facilis et officia qui",
    completed: false
  },
  {
    userId: 1,
    id: 3,
    title: "fugiat veniam minus",
    completed: false
  }
];

const n = 2;

const newArr = arr.filter((x, i) => i < n);
console.log(newArr);
/*
[
  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
  },
  {
    userId: 2,
    id: 2,
    title: "quis ut nam facilis et officia qui",
    completed: false
  }
]
*/

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂