Skip to content

Instantly share code, notes, and snippets.

@ca0v
Created May 8, 2015 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ca0v/3b69ba5f1bd60affd9a5 to your computer and use it in GitHub Desktop.
Save ca0v/3b69ba5f1bd60affd9a5 to your computer and use it in GitHub Desktop.
deep-extend array merge when key values exist
function merge(key: string, ...arrays: Array<any>[]) {
// skip trivial arrays
arrays = arrays.filter(a => !!a && 0 < a.length);
var result = arrays.shift();
if (!arrays.length) return result;
var hash = {}; result.forEach((item, i) => hash[item.id] = i);
arrays.forEach(array => {
array.forEach(item => {
var id = item[key];
if (typeof hash[id] === "undefined") {
hash[id] = result.push(item) - 1;
} else {
result[hash[id]] = deepExtend(result[hash[id]], item);
}
});
});
return result;
}
/*
Modify deepExtend to call merge when two arrays are encountered:
} else if (Array.isArray(val)) {
target[key] = merge("id", target[key], deepCloneArray(val));
return;
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment