0

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?

1
  • Please remove the reactjs tag if the question has nothing to do with ReactJS. Commented Mar 21, 2022 at 6:22

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

As per the question, You should short circuit the age to be null, instead of undefined. Use filteritem.invoiceId===item.invoiceId)[0]?.age || null
Yes, you are right.
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
}
}) 

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.