Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda