Home > Back-end >  Compare one array with a nested array and push value into a new array with same index in Javascript
Compare one array with a nested array and push value into a new array with same index in Javascript

Time:07-22

I have 2 arrays

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

const arrayTwo = [
 {
  data: [
   {
     value: 'Alpha',
     id: '001'
    }
   ],
 {
  data: [
    {
     value: 'Bravo',
     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 newArr = [null, 'Bravo', null]

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

CodePudding user response:

This seems difficult at first because of how arrayTwo is structured. We can make our lives much easier by converting it into a dictionary, then we can just map arrayOne to get our results.

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

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

const dict = {};

arrayTwo.forEach((obj) => {
  let key = obj.data[0].id
  let value = obj.data[0].value
  dict[key] = value
 }
)

const result = arrayOne.map(obj => (dict[obj.id] || null))
console.log('Output: ', result)
console.log('Dictionary:', dict)
This can also be done with Array.prototype.reduce():

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

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

const dict = arrayTwo.reduce((output, obj) => {
  let key = obj.data[0].id
  let value = obj.data[0].value
  output[key] = value
  return output
}, {})   // dict = {'001':'Alpha', '202': 'Bravo'}

const result = arrayOne.map(obj => (dict[obj.id] || null))
console.log(result)

CodePudding user response:

  • Use map to iterate over each element of arr1 and return a new array.
  • Reassemble the data attribute array of each element in the arr2 array using map and flat
  • When arr1 traverses, you can get the current element id, use filter to filter the combined data array, and return an element array that matches the current element id.
  • Based on the case where the id is not matched, use the optional chain operator to get the value.
  • When returning
    1. if you want to get the element array of the id and value attributes, use conditional (ternary) operator, when it doesn't match, return the original element, when it matches, use spread syntax, copy the current element attribute, and add the value attribute
    2. if you only want to get an array of matching results, just return the value, remember to use the optional chain operator to convert the unmatched value to null.

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

const arr2 = [
  { data: [{ value: 'Alpha', id: '001' }] },
  { data: [{ value: 'Bravo', id: '202' }] }
];

const result1 = arr1.map(o1 => {
  const data = arr2.map(o2 => o2.data).flat();
  const value = data.filter(o2 => o2.id === o1.id)[0]?.value;
  return value ? {...o1, value} : o1;
});

const result2 = arr1.map(o1 => {
  const data = arr2.map(o2 => o2.data).flat();
  const value = data.filter(o2 => o2.id === o1.id)[0]?.value;
  return value ?? null;
});

[result1, result2].forEach(r => console.log(JSON.stringify(r)));

CodePudding user response:

You can try this easy line of code :

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

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

let result = arrayOne.map(el => {
    let found = arrayTwo.find(f => f.data.at(0)?.id == el.id)?.data.at(0)?.value;
    return { id: el.id, value: found ?? null};
});

console.log(result);

  • Related