Implement a Value Remover Function - Implement a Value Remover Function

Tell us what’s happening:

Not sure why this removes some items but not others

Your code so far

function destroyer(arr1, ...rest) {
  for (let item in arr1) {
    let currentItem = arr1[item];
    console.log(`On ${currentItem}`);
    if (rest.includes(currentItem)) {
      console.log(`Removing ${currentItem}`);
      arr1.splice(item, 1);
    };
  };
  return arr1;
}

console.log(destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan"));

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36

Challenge Information:

Implement a Value Remover Function - Implement a Value Remover Function

it happens if you change the array you are iterating over

like, let’s say we have array [1,2,4,5,6,8] and we need to remove even numbers that are
index 0 - there is 1, it’s not even, it stays here
index 1 - there is 2, we need to remove this. Now the array is [1,4,5,6,8]
index 2 - there is 5, it’s not even, it stays here
index 3 - there is 6, we need to remove this. Now the array is [1,4,5,8]
index 4 - there isn’t an index 4, array ended. Result is [1,4,5,8]

do you notice what happened? the 4 went to index 1, which was already checked, so it was skipped. Same for the 8

function destroyer(arr1, ...rest) {

  let count = 0;

for (let item of arr1) {

console.log(`On ${item}`);

if (rest.includes(item)) {

console.log(`Removing ${item}`);

arr1.splice(count, 1);

count - 1;

    };

count += 1;

  };

return arr1;

}

Not sure how to fix that

I don’t know how to get the index of an element from the element

then use a way in which you know how to get the index, but stop using splice

1 Like

i suggest that you use the for loop becoz the for…of loop is kinda complicated the apply the push method on those elements which aren’t in the array, happy coding camper!

Alternatively you can use the filter method on the array coupled with the includes method then return the result, happy coding :grinning_face: