Skip to content Skip to sidebar Skip to footer

Merge Array With Unique Keys

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', v

Solution 1:

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;
    })(newSet), []);

console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 2:

You can simply use Array.reduce() to create a map of the old Array and group by combination of name and label. Than iterate over all the elements or objects of the new Array and check if the map contains an entry with given key(combination of name and label), if it contains than simply update it values with the values of new array object, else add it to the map. Object.values() on the map will give you the desired result.

let newArray = [ {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}, {name: 'test', label: 'testlabel', values: [1,2,3,4]} ];

let oldArray = [ {name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]}, {name: 'test', label: 'testlabel', values: [1,2,3,4,5]} ];

let map = oldArray.reduce((a,curr)=>{
  a[curr.name +"_" + curr.label] = curr;
  return a;
},{});

newArray.forEach((o)=> {
  if(map[o.name +"_" + o.label])
    map[o.name +"_" + o.label].values = o.values;
  else
    map[o.name +"_" + o.label] = o;
});
console.log(Object.values(map));

Solution 3:

In your first while loop

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

i and j always have the same value, you are only comparing entries at the same positions in the arrays. If they have different lengths, you stop comparing after the shorter array ends. Your second while-loop will only be executed if newArray is larger than oldArray.

One possible solution is to copy the oldArray, then iterate over newArray and check if the same value exists.

functionmergeArrayWithLatestData (newData, oldData) {
  let arr = oldData;
  for(let i = 0; i < newData.length; i++) {
    let exists = false;
    for(let j = 0; j < oldData.length; j++) {
      if(newData[i].name === oldData[j].name && newData[i].label === oldData[j].label) {
        exists = true;
        arr[j] = newData[i];
      }
    }
    if(!exists) {
      arr.push(newData[i]);
    }
  }
  return arr;
}

var newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}, 
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
]

var oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]}, 
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
]

console.log(mergeArrayWithLatestData(newArray, oldArray));

Solution 4:

You make copies of the original arrays, and in the first one, or change the element, or add:

functionmergeArrayWithLatestData (a1, a2) {
  var out = JSON.parse(JSON.stringify(a1))
  var a2copy = JSON.parse(JSON.stringify(a2))
  a2copy.forEach(function(ae) {
    var i = out.findIndex(function(e) {
        return ae.name === e.name && ae.label === e.label
    })
    if (i!== -1) {
        out[i] = ae
    } else {
        out.push(ae)
    }
  })
  return out
}

[ https://jsfiddle.net/yps8uvf3/ ]

Solution 5:

This is Using a classic filter() and comparing the name/label storing the different pairs using just +. Using destructuring assignment we merge the two arrays keeping the newest first, so when we check the different the newest is always the remaining.

var newArray = [{ name: "abc", label: "abclabel", values: [1, 2, 3, 4, 5] },{ name: "test", label: "testlabel", values: [1, 2, 3, 4] }];

var oldArray = [{ name: "oldArray", label: "oldArrayLabel", values: [1, 2, 3, 4, 5] },{ name: "test", label: "testlabel", values: [1, 2, 3, 4, 5] }];

var diff = [];

oldArray = [...newArray, ...oldArray].filter(e => {

  if (diff.indexOf(e.name + e.label) == -1) {
    diff.push(e.name + e.label);
    returntrue;
  } else {
    returnfalse; //<--already exist in new Array (the newest)
  }

});

console.log(oldArray);

Post a Comment for "Merge Array With Unique Keys"