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

107
Views
push into new array based on id - Javascript

how to create new array based on the two different arrays with same id in Typescript/JavaScript?

let array1 = [
{
invoiceId: 1,
name:'Ajay',
contact:'0001'
},
{
invoiceId: 2,
name:'vijay',
contact:'1234'
},
{
invoiceId: 3,
name:'Amit',
contact:'4581'
},
];

let array2 = [
{
invoiceId: 1,
age:24,
email:'1223@gmail.com'
},
{
invoiceId: 2,
age:23,
email:'23gmail@gmail.com'
},
];

in both array the common field is invoice id based on invoiceid have to create new array as example give below.

let expectedresult = [
{
name:'Ajay',
age:24
},
{
name:'vijay',
age:23
},
{
name:'Amit',
age:null
},
];

how to handle this in Typescript/JavaScript. is there any solution based on Lodash?

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

0

I think this can be one solution.

   let array1 = [
        {
        invoiceId: 1,
        name:'Ajay',
        contact:'0001'
        },
        {
        invoiceId: 2,
        name:'vijay',
        contact:'1234'
        },
        {
        invoiceId: 3,
        name:'Amit',
        contact:'4581'
        },
    ];

    let array2 = [
        {
        invoiceId: 1,
        age:24,
        email:'1223@gmail.com'
        },
        {
        invoiceId: 2,
        age:23,
        email:'23gmail@gmail.com'
        },
    ];
    console.log(array1.map(item=>({name:item.name, age: array2.filter(filteritem=>filteritem.invoiceId===item.invoiceId)[0]?.age || null})))

about 4 years ago · Juan Pablo Isaza Report

0

You have to map through array1 and find the match in array2. Then return name & age if found.

let expectedresult = array1.map(el => {
  let match = array2.find(obj => obj.invoiceId === el.invoiceId)
  return {
    name: el.name,
    age: match ? match.age : null
  }
})
about 4 years ago · Juan Pablo Isaza Report

0

You can create an object map from array2 based on invoiceId as its key and then easily access it while iterating over array1.

const map2 = Object.fromEntries(array2.map(item=>[item['invoiceId'], item.age]))
const expectedArray = array1.map(item=> {
return {
name: item.name,
age: map2[item.invoiceId] ? map2[item.invoiceId] : null
}
}) 
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!