Remove Specific Value From Array in JavaScript

March 3rd, 2023

Few ways to remove specific value from array:

filter, slice, indexOf + splice, lodash / underscore (_pull, _pullAt, _without), delete

filter

filter in everything but value 3 (filter out value 3)

1const value = 3
2const arr = [1, 2, 3, 4, 5, 3]
3 
4arr = arr.filter(function(el) {
5 return el !== value
6})
7 
8// with arrow functions
9arr = arr.filter(el => el !== value)
10 
11console.log(arr) // [ 1, 2, 4, 5 ]

filter out index 3

1const index = 3
2 
3array.filter((el, idx) => idx !== index)

filter + includes

filter out multiple values at once

1let arrToDelete = [2, 3, 5]
2let arr = [1, 2, 3, 4, 5, 3]
3 
4arr = arr.filter(item => !arrToDelete.includes(item))
5 
6console.log(arr) // [ 1, 4 ]

slice

1arr.slice(indexStart, indexBeforeSlice)

indexOf + splice

splice modifies original array and returns removed elements

remove only the first value of 5 (because indexOf finds only first indexOf value 5):

1const array = [2, 5, 9];
2const index = array.indexOf(5); // 1
3 
4if (index > -1) { // only splice array when item is found
5 array.splice(index, 1); // 2nd parameter means remove one item only
6}
7 
8// array = [2, 9]
9 
10// only removes 1st value of 5
1array.splice(indexStart, numberOfItemsToDelete, 'Item Add')
2 
3// At position 2 remove 2 items
4array.splice(2, 2)
5 
6// At position 2, remove 0 items, Add 2 items
7array.splice(2, 0, 'Item1', 'Item2')

remove all values 5

1const value = 5
2const arr = [1,5,2,5,3,5]
3 
4for (let i = 0; i < arr.length; i++) {
5 if (arr[i] === value) {
6 arr.splice(i, 1);
7 i--;
8 }
9 }

underscore / lodash: _pull, _pullAt, _without

1let array = ['a', 'b', 'c', 'd']
2_.pull(array, 'c')
3 
4console.log(array) // ['a', 'b', 'd']
5 
6let array2 = ['e', 'f', 'g', 'h']
7_.pullAt(array2, 0)
8 
9console.log(array2) // ['f', 'g', 'h']
10 
11let array3 = ['i', 'j', 'k', 'l']
12let newArray = _.without(array3, 'i') // ['j', 'k', 'l']
13 
14console.log(array3) // ['i', 'j', 'k', 'l'] doesnt mutate original array

delete

you get undefined values

1let cities = ['Rio', 'London', 'Berlin', 'Ny']
2let removed = delete cities(2);
3 
4console.log(cities) // ['Rio', 'London', undefined, 'Ny']