Home > Enterprise >  how to change the value with the another array value if it matched with the another array value
how to change the value with the another array value if it matched with the another array value

Time:04-14

Hii here is my simple logical question

this is my reference array

referenceArray =[{name : "animal" , source :['duck', 'cat'], target:['water', 'ground']},
                 {name : "car" , source :['tata', 'kia'], target:['tiago', 'sector']},
                 {name : "bike" , source :['honda', 'hero'], target:['livo', 'xtream']}
                    ]

this is i want to modify the source and target array with the above referenceArray array

 originalArray =[{source : 'water' , target : 'hero'},
                 {source : 'tata' , target : 'ground'},
                 {source : 'livo' , target : 'kia'},
                ]

but i want the final output like this

originalArray =[{source : 'animal' , target : 'bike'},
                {source : 'car' , target : 'animal'},
                {source : 'bike' , target : 'car'},
               ]

can anyone help me out please that is soo appreciatable

CodePudding user response:

You can simply build a Map of the reference array with each source and target elements keyed against the name, then map over the originalArray accessing the Map. Keep in mind this does nothing to avoid possible overlap of source and target arrays.

const referenceArray = [{ name: "animal", source: ['duck', 'cat'], target: ['water', 'ground'] }, { name: "car", source: ['tata', 'kia'], target: ['tiago', 'sector'] }, { name: "bike", source: ['honda', 'hero'], target: ['livo', 'xtream'] }];
const originalArray = [{ source: 'water', target: 'hero' }, { source: 'tata', target: 'ground' }, { source: 'livo', target: 'kia' },]

const referenceMap = new Map()
for (const { name, source, target } of referenceArray) {
  for (const k of [...source, ...target]) {
    referenceMap.set(k, name);
  }
}

const result = originalArray.map(({ source, target }) => (
  {
    source: referenceMap.get(source),
    target: referenceMap.get(target)
  }
));

console.log(result)

  • Related