Languages
[Edit]
EN

JavaScript - remove many elements from array by index

12 points
Created by:
Wiktor-Sribiew
800

In JavaScript, it is not intuitive at the first time how to remove elements by index. Remove elements by index operation can be achieved with Array.prototype.splice method. This article is focused on how to do it.

1. Remove elements by index with Array.prototype.splice method example

// ONLINE-RUNNER:browser;

//  index:    0    1    2    3
var array = ['a', 'b', 'c', 'd'];

// removing sice 1st index, 2 elements
var removedElements = array.splice(1, 2);

console.log(array);
console.log(removedElements);

Output (with NodeJS):

[ 'a', 'd' ]
[ 'b', 'c' ]

Notes about Array.prototype.splice method:

  • takes as first argument index of remved element
  • takes as second argument number of removed elements
  • modifies array by removing elements and returns them as array of removed elements

References

  1. Array.prototype.splice method - MDN Docs 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join