I want to remove some elements from the array containing the word Evil (filterString).
JavaScript
x
17
17
1
let guests = ["Partner", "Evil Nice Relative 1", "Nice Relative 2", "Evil One", "another evil", "another one", "another evil is here", "strange Evil is here", "someone Nicer", "Ugly Evil Bad"];
2
3
const filteredArray = [];
4
const filterString = "Evil";
5
6
function checkEvil() {
7
guests.filter((element, index) => {
8
if (element.toLowerCase().indexOf(filterString.toLowerCase()) !== -1) {
9
console.log(index);
10
guests.splice(index,1);
11
} else {
12
filteredArray.push(element);
13
}
14
});
15
console.log(guests);
16
}
17
Here is what I get for the original array (guests):
['Partner', 'Nice Relative 2', 'another evil', 'another one', 'strange Evil is here', 'someone Nicer']
Just want the guests array updated once the desired string (Evil) is filtered.
Advertisement
Answer
Since you want to mutate the original array then you can do as:
JavaScript
1
26
26
1
let guests = [
2
"Partner",
3
"Evil Nice Relative 1",
4
"Nice Relative 2",
5
"Evil One",
6
"another evil",
7
"another one",
8
"another evil is here",
9
"strange Evil is here",
10
"someone Nicer",
11
"Ugly Evil Bad",
12
];
13
14
const filterString = "Evil";
15
16
function checkEvil() {
17
for (let i = guests.length - 1; i >= 0; i--) {
18
const element = guests[i];
19
if (element.toLowerCase().indexOf(filterString.toLowerCase()) !== -1) {
20
guests.splice(i, 1);
21
}
22
}
23
console.log(guests);
24
}
25
26
checkEvil();
1) You can easily achieve the result using filter
and match
as:
JavaScript
1
10
10
1
const arr = [
2
"Partner",
3
"Nice Relative 2",
4
"another evil",
5
"another one",
6
"strange Evil is here",
7
"someone Nicer",
8
];
9
const result = arr.filter((s) => !s.match(/evil/i));
10
console.log(result);
2) You can also do this using forEach and match as:
JavaScript
1
23
23
1
let guests = [
2
"Partner",
3
"Evil Nice Relative 1",
4
"Nice Relative 2",
5
"Evil One",
6
"another evil",
7
"another one",
8
"another evil is here",
9
"strange Evil is here",
10
"someone Nicer",
11
"Ugly Evil Bad",
12
];
13
14
const filteredArray = [];
15
const filterString = "Evil";
16
17
function checkEvil() {
18
guests.forEach(element => {
19
if (!element.match(/evil/i)) filteredArray.push(element);
20
});
21
}
22
checkEvil();
23
console.log(filteredArray);