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.
In this example, we use filter()
method to remove the first occurrence of 'a'
element from array
.
xxxxxxxxxx
1
let array = ['a', 'a', 'b', 'c'];
2
3
array = array.filter((element) => element !== 'a');
4
5
console.log(array); // [ 'b', 'c' ]
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.
xxxxxxxxxx
1
const array = ['a', 'a', 'b', 'c'];
2
3
const elementToRemove = 'a';
4
const index = array.indexOf(elementToRemove);
5
6
if (index !== -1) {
7
const removedElements = array.splice(index, 1); // removes elementToRemove
8
console.log(removedElements); // ['a']
9
}
10
11
console.log(array); // [ 'a', 'b', 'c' ]