JSFiddle - React, Tailwind, and code Playground
JavaScript
var first = [{
id: 1,
name: 'first'
}, {
id: 2,
name: 'second'
}, {
id: 3,
name: 'third'
}]
var second = [{
id: 2,
field: 'foo2'
}, {
id: 3,
field: 'foo3'
}, {
id: 4,
field: 'foo4'
}]
var third = [{
id: 2,
data: 'some2'
}, {
id: 4,
data: 'some4'
}, {
id: 6,
data: 'some6'
}]
var fourth = [{
id: 12,
data: 'some12'
}, {
id: 14,
field: 'some14'
}, {
id: 16,
name: 'some6'
}]
function merge(a, b) {
var key;
if (a && b) {
for (key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
}
return a;
}
function concatenate() {
var result = [];
var args = arguments[0];
for (var i = 0, l = args.length; i < l; i++) {
result = result.concat(args[i]);
}
return result;
}
// return a default object
function getDefault() {
return {
id: undefined,
name: undefined,
data: undefined,
field: undefined
};
}
// loop over the array and check the id. Add the id as a key to
// a temporary pre-filled default object if the key
// doesn't exist, otherwise merge the existing object and the
// new object
function createMergedArray(result) {
var temp = {};
var out = [];
for (var i = 0, l = result.length; i < l; i++) {
var id = result[i].id;
if (!temp[id]) temp[id] = getDefault();
merge(temp[id], result[i]);
}
// loop over the temporary object pushing the values
// into an output array, and return the array
for (var p in temp) {
out.push(temp[p]);
}
return out;
}
function mergeAll() {
// first concatenate the objects into a single array
var concatenated =...