I have an array type Person that has some data. Example:
const people = [{name: "John", age: "18"},{name: "Mike", content: "20"},{label: "Brand", content: "18"},{label: "Alice", content: "50"},{label: "Zina", content: "10"}];
I have another array type of string[] that has the following data:
names=["John", "Zina"]
;
I try to delete the names that are on the second array from the first array like this:
for (let i = 0; i < people.length; i++) {
for (let j = 0; j < names.length; j++) {
if (names[j] === people[i].name) {
people.splice(i);
}
}
}
Why it does not work?
Splice is modifying the original array. i.e. on each iteration if condition return true, people array at that index gets replaced with undefined and hence gets error.
you can use slice method to get data that you want to delete.
for (let i = 0; i < people.length; i++) {
for (let j = 0; j < names.length; j++) {
if (names[j] === people[i].name) {
console.log("matched",names[j],people[i].name, people.slice(i,i+1),);
}
}
}
or you can simply filter data using Filter method.