This tutorial shows how to remove specific item from an array. In JavaScript, we can achieve this by using two ways.
- ECMAScript 5 using
filter
- Using
indexOf
andsplice
Example 1: ECMAScript 5 using filter
let removeValue = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== removeValue
})
console.log(arr)
This can remove multiple items from the array with the same value using the filter()
method.
Output
[ 1, 2, 4, 5 ]
Example 2: Using indexOf
and splice
const array = [1, 2, 3, 4, 5];
let removeValue = 3;
const index = array.indexOf(removeValue);
if (index > -1) {
array.splice(index, 1);
}
console.log(array);
This way can only remove single value. The indexOf()
method gets the position of the value to be removed. The splice()
method removes single value from that point.
Output
[ 1, 2, 4, 5 ]