user1234
user1234

Reputation: 3159

Compare 2 arrays with nested for loops

I have 2 arrays:

a = [{name:"test3", input:[{val:3}]}, {name:"ss", input:[{val:84}]},{name:"sss", input:[{val:86}]},{name:"test", input:[{val:6}]}, {name:"some", input:[{val:8}]}]

a2 = [{name: "dd", field:3},{name: "dd", field:6}]

Now I'm trying to get unique values from both the arrays using `

filter:

    a.forEach(function(i){
 i.input.forEach(function(j){
  a2.filter(function(k){return j.val !== k.field;});
});}) 

and then I want to use: forEach(function(p){p.remove()}); //remove the unique values

so I'm comaparing the val value from first array to the field value in the second one:

the expected outcome:

[{name:"ss", input:[{val:84}]},{name:"sss", input:[{val:86}]},{name:"some", input:[{val:8}]}]  // these are the ones whose `val` from `a` does not match with the `field` from `a2`

The above code returns nothing, any idea what could be missing?

Upvotes: 1

Views: 636

Answers (2)

chevybow
chevybow

Reputation: 11958

Filter the first array based on finding if an element with that input val exists in the second array through a double filter:

let a = [{name:"test3", input:[{val:3}]}, {name:"ss", input:[{val:84}]},{name:"sss", input:[{val:86}]},{name:"test", input:[{val:6}]}, {name:"some", input:[{val:8}]}]

let a2 = [{name: "dd", field:3},{name: "dd", field:6}]

let results = a.filter(e => {
    return a2.filter(q => q.field === e.input['val']).length < 1;
});

console.log(results)

Upvotes: 1

Aramil Rey
Aramil Rey

Reputation: 3475

I think there is a simpler approach:

  1. Create a list of the values you will use to filter your data.
  2. Filter your data with it.

const a = [{name: "test3", input: [{val: 3 }] }, {name: "ss", input: [{val: 84 }] }, {name: "sss", input: [{val: 86 }] }, {name: "test", input: [{val: 6 }] }, {name: "some", input: [{val: 8 }] } ]; 
const a2 = [{name: "dd", field: 3 }, {name: "dd", field: 6 }];

const filterBy = a2.map(v => v.field); // [3, 6]
const res = a.filter(el => !el.input.some(input => filterBy.includes(input.val)))

console.log(res)

Upvotes: 3

Related Questions