Logo

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

Grabbing the first N elements of an array is a straightforward but common operation. Below are a few ways to do it, each with different implications regarding whether you modify the original array or create a new one.

1. Using slice()

If you just want a new array containing the first N elements, slice() is usually the go-to method:

const arr = [1, 2, 3, 4, 5]; const N = 3; // Get first N elements (non-mutating) const firstN = arr.slice(0, N); console.log(firstN); // [1, 2, 3] console.log(arr); // [1, 2, 3, 4, 5] (original unchanged)
  • Pros:
    • Doesn’t modify the original array.
    • Very clean, concise syntax.
  • Cons:
    • Requires creating a new array, which is usually fine for typical use cases.

2. Using splice()

If you want to remove the first N elements from the original array (in place), you can use splice():

const arr = [1, 2, 3, 4, 5]; const N = 3; // Remove the first N elements from arr const removed = arr.splice(0, N); console.log(removed); // [1, 2, 3] console.log(arr); // [4, 5]
  • Pros:
    • Mutates the array in place, which is handy if that’s your goal.
  • Cons:
    • Destructive operation. The original array no longer has those elements.

3. Destructuring (For Quick Extraction)

If you only need to extract the first N elements and perhaps ignore the rest, you can leverage destructuring (though it’s usually more helpful if N is small or known at code time):

const arr = [1, 2, 3, 4, 5]; // For example, if you only need the first 2 elements: const [first, second] = arr; console.log(first, second); // 1 2
  • Pros:
    • Clean syntax for small, fixed N.
  • Cons:
    • Not dynamic if N varies or is large.

4. Using a Loop (Rarely Necessary)

If you need extra processing or more control (e.g., conditionally taking certain elements), a loop is always an option:

const arr = [1, 2, 3, 4, 5]; const N = 3; const firstN = []; for (let i = 0; i < N && i < arr.length; i++) { firstN.push(arr[i]); } console.log(firstN); // [1, 2, 3]
  • Pros:
    • Maximum control for more complex logic.
  • Cons:
    • More verbose for the simple case of “first N elements.”

Performance Considerations

  • Time Complexity: In most JavaScript engines, slicing or splicing is generally O(N), where N is the number of elements you extract. That’s typically acceptable unless your arrays are extremely large.
  • Space Complexity: Using slice() creates a new array of size N in memory. Using splice() modifies the array in place but also creates a temporary array for the removed elements.

Best Practice

For most scenarios, slice(0, N) is the simplest and most common approach if you want a non-mutating way to get the first N items. If you genuinely need to alter the original array, use splice(0, N). Choose whichever approach fits the desired data flow in your application.

Level Up Your JavaScript Knowledge

If you’d like to solidify your understanding of arrays, ES6+ features, and best practices, check out these resources from DesignGurus.io:

For more practice and personalized feedback, you can book a Coding Mock Interview with ex-FAANG engineers or explore the DesignGurus YouTube Channel for video tutorials on coding and system design.

Bottom Line: For a simple, non-mutating solution, slice(0, N) is often the best way to get the first N elements from an array. If you’re okay modifying the original array, splice(0, N) can also work. Choose based on your needs for immutability and clarity!

CONTRIBUTOR
TechGrind