• Post category:JavaScript
  • Reading time:4 mins read

In this tutorial, we’ll look at how to obtain the first N elements from an array in JavaScript. There are a few different ways to obtain N items from an array using JavaScript, but we’ll go through two of them.

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

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

1. slice() method

We’ll use the slice() function to obtain the top 5 elements from an array in this method. It’s the most convenient way to obtain stuff.

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

We can also obtain the first N number of entries from the list using the filter() function. To filter the records, we’ll need to use the element index.

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..!!

Leave a Reply