Search code examples
javascriptarraysecmascript-6nested-loops

Compare one array with a nested array and push value into a new array with same index in Javascript


I have 2 arrays

const arrayOne = [
 {id: '110'},
 {id: '202'},
 {id: '259'}
];

const arrayTwo = [
 {data: [{value: 'Alpha', id: '001'}]},
 {data: [{value: 'Bravo', id: '202'}]},
 {data: [{value: 'Charlie', id: '110'}]},
 {data: [{value: 'Delta', id: '202'}]}
];

I need to create a new array comparing arrayOne[idx].id with arrayTwo[idx].data[idx2].id

Upon match, I need to create an array pushing value (arrayTwo[idx].data[idx2].value) to the new array against each index in arrayOne.

In this example, I would get newArray = [null, 'Bravo', null, Delta]

What I have tried:

arrayOne.map(item => ({
   ...item,
   result: arrayTwo.filter(itemTwo => item.data.map(x => x.id).includes(itemTwo.id))
}));

and also

const newArr = [];
arrayOne.map((item, idx) => {
   if (arrayTwo.filter(itemTwo => itemTwo.data?.map(x => x.id) === item.id)) {
     newArr.push(arrayTwo.data[idx].value);
   } else newArr.push(null);
 });

Solution

  • To do this you can map arrayTwo and use .find() to search for the ID in arrayOne. I also mapped arrayTwo to the inner object to make the second map more concise.

    const arrayOne = [
     {id: '110'},
     {id: '202'},
     {id: '259'}
    ];
    
    const arrayTwo = [
     {data: [{value: 'Alpha',id: '001'}]},
     {data: [{value: 'Bravo',id: '202'}]}, 
     {data: [{value: 'Charlie',id: '777'}]},
      {data: [{value: 'Delta',id: '202'}]}
    ];
    
    const result = arrayTwo
      .map(obj => obj.data[0])
      .map(obj => (arrayOne.find(v => v.id === obj.id) && obj.value) || null)
      
    console.log(result)