ganesh kaspate
ganesh kaspate

Reputation: 2695

Compare and return boolean if two array of objects has the values or not

I have two array of objects which are like,

let A = [{id: "1"}, {id: "2"},{id: "3" }]

let B = [{id: "3"}, {id: "2"}]

Now, I am iterating over A.

return _.map(A) => ({
    id: A.id,
    isAvaliable: //This needs to be like weather B includes A on the basis of ID , means does B object has this A client ID if yes then set it true or false
})

So, final object which I will get will be,

const result = [{
{id: "1", isavaliable: false},
{id: "2", isavaliable: true},
{id: "3", isavaliable: true},

}
]

So, How do I achieve this ? Thanks.

Upvotes: 0

Views: 1046

Answers (3)

Vinay
Vinay

Reputation: 2339

Use lodash 'find' to check id in array B

const A = [{id: '1'}, {id: '2'}, {id: '3' }];
const B = [{id: '3'}, {id: '2'}];

const C = _.map(A, item => {

        return {
            id: item.id,
            isAvailable: _.find(B, {id: item.id}) ? true : false
        };
    });

Upvotes: 1

xdeepakv
xdeepakv

Reputation: 8135

let A = [{ id: "1" }, { id: "2" }, { id: "3" }];

let B = [{ id: "3" }, { id: "2" }];

const merge = (arr1, arr2) =>
  arr1.map((a) => ({
    id: a.id,
    isAvaliable: !!arr2.find((b) => b.id === a.id),
  }));
console.log(merge(A, B));

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371203

First make an array or Set of the B ids, then you can .map A and set isavailable by whether the id is included in the set:

const A = [{id: "1"}, {id: "2"},{id: "3" }];
const B = [{id: "3"}, {id: "2"}];
const haveIds = new Set(B.map(({ id }) => id));

const result = A.map(({ id }) => ({ id, isavailable: haveIds.has(id) }));
console.log(result);

No need to rely on an external library, Array.prototype.map works just fine.

Upvotes: 1

Related Questions