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

109
Views
How to compare/match id's in two seperate arrays, and retrieve some data into one object in javascript?

I have the following values -

const r = [{ id: 2, car: 'toyota}, {id: 1, car:'honda'}]

const s = [{ id: 2, name: 'Samuel'},{id: 1, name: 'James'}]

I want to match the arrays based on id and add name to each corresponding matched object id.

const res = [{id: , car: , name: }]

I have certain values I need to map together to make into one response object, so it needs to be an array of objects with various properties. I want to map based on an id and then loop through each object in the array and add the corresponding object. Kindly help, much appreciated!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can easily achieve the result using Map and map

const r = [
  { id: 2, car: "toyota" },
  { id: 1, car: "honda" },
];

const s = [
  { id: 2, name: "Samuel" },
  { id: 1, name: "James" },
];

const map = new Map(r.map((o) => [o.id, o]));
const result = s.map((o) => ({ ...o, ...(map.get(o.id) ?? []) }));
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

In this problem we need to filter the data & also need to map the data so for this direct filter operator won't work so I just solved your problem with a forEach loop.

const arr1 = [{ id: 2, car: 'toyota'}, {id: 1, car:'honda'}]

const arr2 = [{ id: 3, name: 'Samuel'},{id: 1, name: 'James'}]

const result = [];
arr1.forEach(arr1Obj=>{
  const matchedObject = arr2.find(arr2Obj=>arr2Obj.id==arr1Obj.id);
  if(matchedObject){
  result.push({...arr1Obj,...matchedObject});
  }
  
})
console.log(result);

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!