0

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.

1
  • your final result is wrong.. please verify. It should be object of array. Commented May 3, 2020 at 4:04

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah but I was trying to do it in one line so that I can return boolean for this . here in this solution we are rreturning the array again
1

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));

Comments

1

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
        };
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.