How do i get the list of items that are in array B (that is made up of objects) but are not in array A .?

JavaScript :

How do i get an array of items that are in array B (that is made up of objects) but are not in array A . For example I have two arrays hackers and developers . Now I would like to get an array that has the developers who are not hackers : something like

resultOfDevelopersWhoAreNotHackers = [{
    name:'Paul',
    id:6
}];

var hackers = [
    {
        name:'Joy',
        id:2
    },
    {
        name:'Peter',
        id:3
    }
];

var developers = [
    {
        name:'Joy',
        id:2
    },
    {
        name:'Paul',
        id:6
    },
    {
        name:'Peter',
        id:3
    }
];

I have tried looping through both but it fills my array twice :

var resultOfDevelopersWhoAreNotHackers = [];
hackers.map((x)=>{

        coders.map((k)=>{
            if(k.id != x.id){
                resultOfDevelopersWhoAreNotHackers.push(x);
            }
        });
    });

Upvotes: 0

Views: 40

Answers (2)

Arman Charan
Arman Charan

Reputation: 5797

Set tends to be useful for problems regarding the unions of arrays.

// Input.
const hackers = [{name:'Joy',id:2},{name:'Peter',id:3}]
const programmers = [{name:'Joy',id:2},{name:'Paul',id:6},{name:'Peter',id:3}]

// Programmers Not Hackers.
const programmersNotHackers = (H, P) => {
  const s = new Set(H.map(h => h.id))
  return P.filter(p => !s.has(p.id))
}

// Output.
const output = programmersNotHackers(hackers, programmers)

// Proof.
console.log(output)

Upvotes: 1

Sikini Joseph
Sikini Joseph

Reputation: 71

Loop through array B while checking the contents of Array A. Also look at the different kinds of joins in this blog post six join implementations in javascript

Upvotes: 1

Related Questions