0

I have two arrays of objects like this:

var myArray = [
  {pk: '1', person: 'person 1'}, 
  {pk: '2', person: 'someone'}, 
];

var updatedArray = [
  {pk: '2', person: 'another person'}
];

I'm looking to merge the two in the most efficient way possible. My thought was to merge the older myArray into the newer updatedArray and leave out any items where myArray.pk == updatedArray.pk

I'm having trouble trying to get it going with either jQuery or underscore. I've been trying to use this one as an example as well.

Any ideas?

Community
  • 1
  • 1
spikej
  • 136
  • 2
  • 9

4 Answers4

1

I think looping through updates and copy it over to current value would be a good way. If you have just one property to change then there is no need for Object.assign. you can simply replace it with

myArray[idx].name = uv.name

var myArray = [
  {pk: '1', person: 'person 1'}, 
  {pk: '2', person: 'someone'}, 
];

var updatedArray = [
  {pk: '2', person: 'another person'}
];

updatedArray.forEach(uv => {
  var idx = myArray.findIndex(v => v.pk === uv.pk)
  if (idx != -1)
    myArray[idx] = Object.assign({}, myArray[idx], uv);
  else myArray.push(uv);
});

console.log(myArray)
Morteza Tourani
  • 3,506
  • 5
  • 41
  • 48
1

You can try

 function mergeArr(arrOne, arrTwo, prop) {
        _.each(arrTwo, function(arrTwoobj) {
            var arrOneobj = _.find(arrOne, function(arrOneobj) {
                return arrOneobj[prop] === arrTwoobj[prop];
            });
            arrOneobj ? _.extend(arrOneobj, arrTwoobj) : arrOne.push(arrTwoobj);
        });
    }

    var myArray = [
      {pk: '1', person: 'person 1'}, 
      {pk: '2', person: 'someone'}, 
    ];

    var updatedArray = [
      {pk: '2', person: 'another person'}
    ];

    mergeArr(myArray, updatedArray, 'pk');
    console.log(myArray);
Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70
1

var myArray = [
  {pk: '1', person: 'person 1'}, 
  {pk: '2', person: 'someone'}, 
];

var updatedArray = [
  {pk: '2', person: 'another person'}
];

var exists = [];
for (item of updatedArray) {
  exists[item.pk] = true;
}
for (item of myArray) {
  if (!exists.hasOwnProperty(item.pk)) {
    updatedArray.push(item);
  }
}

console.log(updatedArray);
Leonid Zakharov
  • 940
  • 1
  • 6
  • 11
0

Most efficient way would be, first create a map from one of the arrays. Then run one loop and get the items from the map

you need just two functions, reduce and map

This way only need array1.length + array2.length iterations, not array1.length * array2.length

// creates the map
var myMap = myArray.reduce(function(obj, item) {
  obj[item.pk] = item
}, {})

// merges updatedArray items, with the item from the map
var mergedArray = updatedArray.map(function(item) {
   return myMap[item.pk] ? Object.assign({}, myMap[item.pk], item) : item
})
webdeb
  • 12,993
  • 5
  • 28
  • 44