JavaScript - merge two arrays of objects and de-duplicate based on property value
I came here looking for exactly this, saw @Gruff Bunny 's technique and wondered if 'lodash' wouldn't perhaps be a superior option even to 'underscore'?
Lo and behold :
let result = _.unionBy(updatingArr, origArr, 'name');
Using a double for loop and splice you can do it like so:
for(var i = 0, l = origArr.length; i < l; i++) {
for(var j = 0, ll = updatingArr.length; j < ll; j++) {
if(origArr[i].name === updatingArr[j].name) {
origArr.splice(i, 1, updatingArr[j]);
break;
}
}
}
Example here
You could use Array#map
in combination with Array#reduce
var origArr = [{ name: 'Trump', isRunning: true }, { name: 'Cruz', isRunning: true }, { name: 'Kasich', isRunning: true }],
updatingArr = [{ name: 'Cruz', isRunning: false }, { name: 'Kasich', isRunning: false }],
NEWArr = origArr.map(function (a) {
return this[a.name] || a;
}, updatingArr.reduce(function (r, a) {
r[a.name] = a;
return r;
}, Object.create(null)));
document.write('<pre>' + JSON.stringify(NEWArr, 0, 4) + '</pre>');