EN
JavaScript - search and remove string from array
0
points
In this article, we would like to show you how to search and remove string from an array in JavaScript.
1. Remove all occurrences
In this example, we use filter()
method to remove the first occurrence of 'a'
element from array
.
// ONLINE-RUNNER:browser;
let array = ['a', 'a', 'b', 'c'];
array = array.filter((element) => element !== 'a');
console.log(array); // [ 'b', 'c' ]
2. Remove first occurrence
In this example, we use indexOf()
method to get the index of the first elementToRemove
occurrence in array
. Then using splice()
method we remove it.
// ONLINE-RUNNER:browser;
const array = ['a', 'a', 'b', 'c'];
const elementToRemove = 'a';
const index = array.indexOf(elementToRemove);
if (index !== -1) {
const removedElements = array.splice(index, 1); // removes elementToRemove
console.log(removedElements); // ['a']
}
console.log(array); // [ 'a', 'b', 'c' ]