2

I got an Array a = [1,2,3,4,5] and an Array b = [1,3] which contains some elements of a. So it is a kind of a sub array of a.

In this for loop below, I can use the elements of b to "do smething". Now, how can I interact in the same loop with the elements of a that are not a part b? That means 2, 4 and 5 from a? How to filter them out?

function action (){
for (var i=0; i<b.length; i++) {

      b[i].x = "do something";


  } 

Thanks so much"

Suppe
  • 189
  • 2
  • 5
  • 12

3 Answers3

5

You can use the filter() function combined with the includes() function to filter the list:

const diff = a.filter(i => !b.includes(i));

diff will contain just the elements in a that aren't in b.

This is called a difference between the arrays. There are also a lot of libraries that will include a some sort of diff function for arrays.

samanime
  • 25,408
  • 15
  • 90
  • 139
2

You can use filter on your a array to get a new list of elements not contained:

a.filter(item => !b.includes(item)).forEach(function(item) {
    console.log(item);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
2

You are looking for this : a.filter((element) => !b.includes(element))

Sample

const a = [1,2,3,4,5];
const b = [1,3]

const elements_in_a_not_in_b = a.filter((element) => !b.includes(element))

console.log(
  elements_in_a_not_in_b
)
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254