Remove array items from an array in Javascript

I have two array,

arr = [2,5,5,4,5,4,5,4,8,4,5]
delitem = [5,4];

I have to remove those items from arr , which item is in delitem.
Here is the my way,

 var arr = [2,5,5,4,5,4,5,4,8,4,5];
 var delitem = [5,4];
 for(let i = 0; i < arr.length; i++){
   for(let j=0; j < delitem.length; j++){
      if(arr[i] === delitem[j]){
        const index = arr.indexOf(delitem[j]);
        arr.splice(index,1);
      }
   }
 }
console.log(arr);

What I get is,

[ 2, 5, 5, 5, 8, 5 ]

What I’m expecting is,

[2,8]

Please give me some suggestion to fix it :roll_eyes:

You are mutating the array as you iterate over it, which will produce unexpected results. To see that, run this code:

const arr = [2,5,5,4,5,4,5,4,8,4,5];
for (let i = 0; i < arr.length; i++) {
  console.log("i: " + i);
  arr.splice(i, 1);
  console.log(arr);
 }

In this case, I would look at the high-order function .filter(). This is exactly the sort of thing .filter() is built to do.

1 Like

Why it’s not working? :frowning:

var arr = [2,5,5,4,5,4,5,4,8,4,5];
var delitem= [4,5];
for(let i=0; i< delitem.length; i++){
  arr.filter(x => x != delitem[i]);
}
console.log(arr); 

The .filter() method does not modify the array. It instead returns a filtered array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

1 Like

Thank you so much :gift_heart:

var arr = [2,5,5,4,5,4,5,4,8,4,5];
var delitem= [4,5];
for(let i=0; i< delitem.length; i++){
  arr = arr.filter (x => x != delitem[i]);
}
console.log(arr); 
1 Like

What about the small and efficient code?

  let newarray = arr.filter(function(val) {

    return delitem.indexOf(val) == -1;

  });

Also, What about one line of code? (For ES6) - Might not work in IE browser.

let newarray = arr.filter(val => !delitem.includes(val));

Thanks.
Suraj Surve

1 Like

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

2 Likes

Wow :heart_eyes:
It’s cool. Thank you Suraj Surve :hugs: