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

160
Views
How to compare two arrays and return another one?

How to compare two arrays and return another one? I'm trying to compare two arrays to compare records by id and then render a new array

const arr1 = [
  { id: 1, title: "Admin" },
  { id: 2, title: "Vip" }
];

const arr2 = [
  {
    id: 1,
    root: 1
  },
  {
    id: 2,
    root: 0
  }
];

let intersection = arr1.filter(({ id }) => arr2.includes(id));

need:

const needArr = [
  { id: 1, title: "Admin", root: 1 },
  { id: 2, title: "Vip", root: 0 }
];
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You could make use of map() and find() and iterate over the first array arr1:

const needArr = arr1.map(entry => {
    const root = arr2.find(arr2Entry => entry.id === arr2Entry.id)?.root
    return {...entry, root: root}
} )

The root property will be set to undefined for each entry in the needArr result if there is no entry with the same id in arr2 as in arr1.

about 4 years ago · Juan Pablo Isaza Report

0

Something like this could work,


const giveNew = (a, b) => {
    let shorter, longer;
    if(a.length>b.length){
      longer = a;
      shorter = b;
    } else {
      longer = b;
      shorter = a;
    }
  
    return longer.map((v, i)=> {
      const matched = shorter.find(val=> val.id === v.id);
      if(matched){
          return {
          ...v, ...matched
      }
    }
  })
}
about 4 years ago · Juan Pablo Isaza Report

0

Assuming there's a 1:1 relationship between the arrays - map over one of the arrays, find the corresponding object in the other array by its id, and then return a new updated object.

const arr1=[{id:1,title:"Admin"},{id:2,title:"Vip"}],arr2=[{id:1,root:1},{id:2,root:0}];

const out = arr2.map(obj => {
  return {
    ...arr1.find(inner => inner.id === obj.id),
    root: obj.root
  };
});

console.log(out);

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!