Remove an element from an array in javascript

Jun 20, 2024·
Gert de Pagter
Gert de Pagter
· 2 min read

In JavaScript, there are a few ways to remove an element from an array. Depending on whether you want to remove elements by value, by index, or based on a condition, you have different options to choose from.

Using Array.splice() or Array.toSpliced() to remove elements by index

With Array.splice() you can remove an element from an array by telling it from what index you want to start removing and how many. It will also return the removed elements. Array.toSpliced() is similar to Array.splice(), but instead of returning the removed items and deleting them from the original array, it will return a new array where the items are deleted, and not modify the original array. For example:

// splice Example
const ores = ['tin', 'copper', 'iron', 'coal', 'mithril', 'adamant', 'rune'];

// Remove 2 elements starting from index 3
console.log(ores.splice(3,2)); // ['coal', 'mithril']

console.log(ores); // ['tin', 'copper', 'iron', 'adamant', 'rune']
// toSpliced Example
const ores = ['tin', 'copper', 'iron', 'coal', 'mithril', 'adamant', 'rune'];

// Remove 2 elements starting from index 3
console.log(ores.toSpliced(3,2)); // ['tin', 'copper', 'iron', 'adamant', 'rune']

console.log(ores); // ['tin', 'copper', 'iron', 'coal', 'mithril', 'adamant', 'rune']

If you want to remove every item that matches a criteria, you will need another method.

Using Array.filter() to remove element by a condition

With Array.filter we can get an array back which contains all items that match the check we pass it. Unlike Array.splice it won’t change the original array.

const ores = [
  {level: 1, name: 'tin'}, 
  {level: 1, name: 'copper'}, 
  {level: 15, name: 'iron'}, 
  {level: 30, name: 'coal'}, 
  {level: 55, name: 'mithril'},
  {level: 70, name: 'adamant'}, 
  {level: 85, name: 'rune'}
];

const lowLevelOres = ores.filter((ore) => (ore.level < 20));

console.log(lowLevelOres); // [{level: 1, name: 'tin'}, {level: 1, name: 'copper'}, {level: 15, name: 'iron'}]

If you want to get notified of the next blog post, join the newsletter.