10 February 2024

To remove all but the first n elements from an array in JavaScript, you can use the splice() method or array slicing. The splice() method in JavaScript is used to change the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Source code viewer
  1. let array = [1, 2, 3, 4, 5, 6];
  2. array.splice(3); // Removes all elements starting from index 3
  3. console.log(array); // Output: [1, 2, 3]
Programming Language: Javascript