user18525765
user18525765

Reputation: 3

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:'[email protected]'
},
{
invoiceId: 2,
age:23,
email:'[email protected]'
},
];

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?

Upvotes: 0

Views: 193

Answers (3)

Anahit Mkrtchyan
Anahit Mkrtchyan

Reputation: 21

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:'[email protected]'
        },
        {
        invoiceId: 2,
        age:23,
        email:'[email protected]'
        },
    ];
    console.log(array1.map(item=>({name:item.name, age: array2.filter(filteritem=>filteritem.invoiceId===item.invoiceId)[0]?.age || null})))

Upvotes: 2

dev_sanketsr
dev_sanketsr

Reputation: 94

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
}
}) 

Upvotes: 0

Madhan S
Madhan S

Reputation: 693

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
  }
})

Upvotes: 0

Related Questions