Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
JavaScript: add new property to array elements according to another array

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'}
]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!