Remove element from array in javascript

JavaScript offers many ways lớn remove sầu an thành quả from an array. Learn the canonical way, & also find out all the options you have, using plain JavaScript

Published May 02, 2018


Here are a few ways lớn remove an thành quả from an array using JavaScript.

Bạn đang xem: Remove element from array in javascript

All the method described bởi not mutate the original array, & instead create a new one.

If you know the index of an item

Suppose you have an array, and you want khổng lồ remove sầu an tòa tháp in position i.

One method is to use slice():


const items = <'a', 'b', 'c', 'd', 'e', 'f'>const i = 2const filteredItems = items.slice(0, i).concat(items.slice(i + 1, items.length))// <"a", "b", "d", "e", "f">
slice() creates a new array with the indexes it receives. We create a new array, from the start to lớn the index we want to lớn remove, and concatenate another array from the first position following the one we removed to lớn the end of the array.

Xem thêm: Download Your Free Pdf Download Game: Undercover In The Secret Society Of Pick

If you know the value

In this case, one good option is khổng lồ use filter(), which offers a more declarative approach:


const items = <'a', 'b', 'c', 'd', 'e', 'f'>const valueToRemove = 'c'const filteredItems = items.filter(tác phẩm => cống phẩm !== valueToRemove)// <"a", "b", "d", "e", "f">

const items = <'a', 'b', 'c', 'd', 'e', 'f'>const valueToRemove = 'c'const filteredItems = items.filter(function(item) return công trình !== valueToRemove)// <"a", "b", "d", "e", "f">
or you can use Babel and transpile the ES6 code back khổng lồ ES5 lớn make it more digestible to old browsers, yet write modern JavaScript in your code.

Removing multiple items

What if instead of a single thắng lợi, you want khổng lồ remove sầu many items?

Let’s find the simplest solution.

By index

You can just create a function và remove sầu items in series:


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">

const items = <'a', 'b', 'c', 'd', 'e', 'f'>const valuesToRemove sầu = <'c', 'd'>const filteredItems = items.filter(công trình => !valuesToRemove sầu.includes(item))// <"a", "b", "e", "f">

Avoid mutating the original array

splice() (not to be confused with slice()) mutates the original array, & should be avoided.


The 2021 JavaScript Full-Staông xã Bootcamp will start at the end of March 2021. Don"t miss this opportunity, signup khổng lồ the waiting list!

More js tutorials:


*
Free ebooks