How to delete items from an array in JavaScript

JavaScript provides many ways to delete items from an array. Learn the canonical method and use plain JavaScript to find out all available options

There are several waysRemove items from the array using JavaScript.

All described methodsDon't change the original array, But create a new one.

If you know the index of the item

Suppose you have an array and want to delete an item in the appropriate positioni.

One way is to useslice():

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 2
const filteredItems = items.slice(0, i).concat(items.slice(i + 1, items.length))
// ["a", "b", "d", "e", "f"]

slice()Create a new array using the received index. We create a new array from the beginning to the index to be deleted, and then connect another array from the first position after deletion to the end of the array.

If you know the value

In this case, a good option is to usefilter(), It provides moreDeclarativemethod:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
// ["a", "b", "d", "e", "f"]

This will use the ES6 arrow function. You can use traditional features to support older browsers:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
  return item !== valueToRemove
})
// ["a", "b", "d", "e", "f"]

Alternatively, you can use Babel and recompile the ES6 code back to ES5 to make it easier to use by older browsers, but you can still write modern JavaScript in the code.

Delete multiple items

What if you want to delete multiple items instead of a single item?

Let us find the simplest solution.

By index

You can just create a function and delete a series of items:

const items = ['a', 'b', 'c', 'd', 'e', 'f']

const removeItem = (items, i) => items.slice(0, i-1).concat(items.slice(i, items.length))

let filteredItems = removeItem(items, 3) filteredItems = removeItem(filteredItems, 5) //[“a”, “b”, “d”, “e”]

By value

You can search for included items in the callback function:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]

Avoid mutating the original array

splice()(Don’t go withslice()) Changing the original array should be avoided.

Download mine for freeJavaScript beginner's manual


More js tutorials: