简体   繁体   中英

Why splice method does not work and delete item on array in TypeScript

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?

If you like to keep the object reference from people , you could iterate people from the end, because Array#splice with items to delete changes the indices of the following items.

 var people = [{ name: "Mike", content: "20" }, { label: "Brand", content: "18" }, { label: "Alice", content: "50" }, { label: "Zina", content: "10" }], names = ["John", "Zina"], i = people.length; while (i--) { if (names.includes(people[i].name) || names.includes(people[i].label)) { people.splice(i, 1); } } console.log(people);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

The splice method is modifying the array inplace . I suggest you to use filter method.

 const people = [{name: "John", age: "18"},{name: "Mike", content: "20"},{name: "Brand", content: "18"},{name: "Alice", content: "50"},{name: "Zina", content: "10"}], names=["John", "Zina"]; console.log(people.filter(({name}) => !names.includes(name)));

Please refer below Code.

 const people = [{name: "John", age: "18"},{name: "Mike", content: "20"},{label: "Brand", content: "18"},{label: "Alice", content: "50"},{label: "Zina", content: "10"}]; const names = ["Mike","Shiv"]; for (let i = 0; i < people.length; i++) { debugger for (let j = 0; j < names.length; j++) { if (names[j] === people[i].name) { people.splice(i,1); } } } console.log(people)

Splice is modifying the original array. ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM