-4

I have two arrays.

When comparing, if arr1 property id matches with arr2 property id, then add new property tag: assign else add tag: ''

I have tried the below code:

var result = arr1.filter(({ id: id }) => 
  !arr2.some(({ name: name }) => name === id)
);

Sample inputs:

var arr1 = [
  {id:1, name: "ram"},
  {id:24, name: "zen"},
  {id: 3, name: "sam"}
]
var arr2 = [
  {id:24, name: "zen"},
  {id: 3, name: "sam"}
]

Expected Output:

 [
  {id:1, name: "ram", tag:''},
  {id:24, name: "zen", tag: 'yes'},
  {id: 3, name: "sam", tag: 'yes'}
]
2
  • also: JavaScript merging objects by id Commented Feb 12, 2022 at 15:01
  • The duplicate assigned is for merging arrays, not what OP is looking for. Commented Feb 12, 2022 at 15:14

1 Answer 1

-1
  • Create a Set of ids in arr2 using Array#map
  • Again, using Array#map, iterate over arr1 and set tag using Set#has

const 
  arr1 = [ {id:1, name: "ram"}, {id:24, name: "zen"}, {id: 3, name: "sam"} ],
  arr2 = [ {id:24, name: "zen"}, {id: 3, name: "sam"} ];
  
const arr2IdsSet = new Set( arr2.map(({ id }) => id) );

const res = arr1.map(e => ({ ...e, tag: arr2IdsSet.has(e.id) ? 'yes' : '' }));

console.log(res);

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

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.