I want to remove some elements from the array containing the word Evil (filterString).
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"];
const filteredArray = [];
const filterString = "Evil";
function checkEvil() {
guests.filter((element, index) => {
if (element.toLowerCase().indexOf(filterString.toLowerCase()) !== -1) {
console.log(index);
guests.splice(index,1);
} else {
filteredArray.push(element);
}
});
console.log(guests);
}
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.
CodePudding user response:
Since you want to mutate the original array then you can do as:
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",
];
const filterString = "Evil";
function checkEvil() {
for (let i = guests.length - 1; i >= 0; i--) {
const element = guests[i];
if (element.toLowerCase().indexOf(filterString.toLowerCase()) !== -1) {
guests.splice(i, 1);
}
}
console.log(guests);
}
checkEvil();
1) You can easily achieve the result using filter
and match
as:
const arr = [
"Partner",
"Nice Relative 2",
"another evil",
"another one",
"strange Evil is here",
"someone Nicer",
];
const result = arr.filter((s) => !s.match(/evil/i));
console.log(result);
2) You can also do this using forEach and match as:
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",
];
const filteredArray = [];
const filterString = "Evil";
function checkEvil() {
guests.forEach(element => {
if (!element.match(/evil/i)) filteredArray.push(element);
});
}
checkEvil();
console.log(filteredArray);
CodePudding user response:
define a pattern and then filter by it
var arr = ['Partner', 'Nice Relative 2', 'another evil', 'another one', 'strange Evil is here', 'someone Nicer'];
const PATTERN = 'EVIL';
arr = arr.filter(str => str.toUpperCase().indexOf(PATTERN) === -1);
CodePudding user response:
<script>
var list = ['Partner', 'Nice Relative 2', 'another evil', 'another one', 'strange Evil is here', 'someone Nicer'];
var new_list = [];
for(var i=0; i<list.length; i ) {
if(!list[i].toLowerCase().includes('evil')) {
new_list.push(list[i]);
}
}
console.log(new_list);
</script>
CodePudding user response:
You can filter your array where the value of each doesn't contain 'evil'
word:
const arr = ['Partner', 'Nice Relative 2', 'another evil', 'another one', 'strange Evil is here', 'someone Nicer'];
const filteredArr = arr.filter(val=>!val.toLowerCase().includes('evil'))
console.log(filteredArr)