merge array with unique keys

  • A+
Category:Languages

I have array of objects called newArray and oldArray.

Like this : [{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}]

example :  newArray = [ {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},  {name: 'test', label: 'testlabel', values: [1,2,3,4]} ]  oldArray = [ {name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},  {name: 'test', label: 'testlabel', values: [1,2,3,4,5]} ]  result will be = [ {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},  {name: 'test', label: 'testlabel', values: [1,2,3,4]},  {name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]} ]; 

I wanted to merge both the array in such a way that whenever name and label are equal in both the arrays it should only consider newArray value.

I have tried

function mergeArrayWithLatestData (newData, oldData) {   let arr = [];   let i = 0; let j =0   while ((i < newData.length) && (j < oldData.length)) {     if ((findIndex(newData, { name: oldData[i].name, label: oldData[i].label })) !== -1) {       arr.push(newData[i])   } else {     arr.push(newData[i]);     arr.push(oldData[i]);   }   i += 1;   j += 1; } while (i < newData.length) {     arr.push(newData[i]);  }  return arr; } 

But i am not getting correct result.

Any suggestions?

 


You could add all array with a check if name/label pairs have been inserted before with a Set.

var newArray = [{ name: 'abc', label: 'abclabel', values: [1, 2, 3, 4, 5] }, { name: 'test', label: 'testlabel', values: [1, 2, 3, 4] }],     oldArray = [{ name: 'oldArray', label: 'oldArrayLabel', values: [1, 2, 3, 4, 5] }, { name: 'test', label: 'testlabel', values: [1, 2, 3, 4, 5] }],     result = [newArray, oldArray].reduce((s => (r, a) => {         a.forEach(o => {             var key = [o.name, o.label].join('|');             if (!s.has(key)) {                 r.push(o);                 s.add(key);             }         });         return r;     })(new Set), []);  console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: