How to get first N number of elements from an array?

 

You can get the first N number of elements from an array in JavaScript using the slice() method. Here's an example:

javascript
let array = [1, 2, 3, 4, 5, 6]; let n = 3; // Use the slice() method to get the first N elements let firstNElements = array.slice(0, n); console.log("First", n, "elements:", firstNElements);

Output:

less
First 3 elements: [1, 2, 3]

In this example:

  • We have an array called array containing [1, 2, 3, 4, 5, 6].
  • We want to get the first n elements, where n is set to 3.
  • We use the slice(0, n) method to extract elements from index 0 (inclusive) to index n (exclusive), effectively getting the first n elements.

The slice() method returns a new array containing the selected elements without modifying the original array. If you want to modify the original array, you can use the splice() method instead.

Comments