-1

I have an array of integers, and I'm using the .push() method to add elements to it.

Why do I not delete the specified elements from the array when I use splice ()?

var arr = [1001, 1002, 1005, 1006];
var list = [{"id": 1002},{"id": 1005},{"id": 1006},{"id": 1007},{"id": 1008},{"id": 1009},{"id": 1010}];

function inArray(value, arr){
  for (let item in arr) {
    if (list.hasOwnProperty(item)) {
      if (arr[item] === value) {
        return true;
      }    
    }
  }
  return false;
};

for (let item in list) {
  if (list.hasOwnProperty(item)) {
    if (inArray(list[item].id, arr)) {
      list.splice(item, 1);
    }    
  }
};

console.log(list);
mxh861001
  • 25
  • 4

4 Answers4

0

Try this:-

var arr = [1001, 1002, 1005, 1006];
var list = [{"id": 1002},{"id": 1005},{"id": 1006},{"id": 1007},{"id": 1008},{"id": 1009},{"id": 1010}];

function inArray(value){
  for (var i=0; i< arr.length; i++) {
      if (arr[i] === value) {
        return true;
      }    
  }
  return false;
};
var updatedList = [];
for (var i =0; i< list.length; i++) {
    if (!inArray(list[i].id)) {
     updatedList.push(list[i])
    }    
};
console.log(updatedList);
Sagar Kharche
  • 2,577
  • 2
  • 24
  • 34
0

The problem with your code is when you do a .splice() on an array, indexes of the array will also change. That is why you are removing the wrong array element on the next loop.

You can use filter instead.

var arr = [1001, 1002, 1005, 1006];
var list = [{"id": 1002},{"id": 1005},{"id": 1006},{"id": 1007},{"id": 1008},{"id": 1009},{"id": 1010}];

list = list.filter(o => !arr.includes(o.id));

console.log(list);
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

I will not give a code but will explain the reason why you are not getting the expected result. You are changing the list inside the loop iterating over the list. This has problems:

In the first iteration, 1002 is found in arr and your code removes the first entry from list. this is fine.

Second iteration: because you removed the first element of list, the remaining elements' indices decrease by 1. But this time item is 1. And even if you want to remove 1005 from arr, it's new index is 0. So instead 1006 gets deleted.

Third iteation: item is 2 and because you deleted 1002 and 1006, the 2nd element (starting from 0) in list is now 1008, which is not in arr; and nothing is deleted.

As the list changes in size, the total number of iterations will be 5 and NOT 7 because you have deleted two items while looping over list.

solution I suggest: iterate backward.

Tuhin Paul
  • 558
  • 4
  • 11
0

One method is that

function deleteFromArray(list, arr) {
  let copy = []
  list.forEach((item, index) => {
    if (!arr.includes(item.id)) {
        copy.push(item)
    }
  })
  return copy
}

the other is

list.filter(item => {return !arr.includes(item.id)})
jiangyx3915
  • 119
  • 3