Skip to content

Instantly share code, notes, and snippets.

@hperantunes
Last active October 1, 2019 17:38
Show Gist options
  • Save hperantunes/14580610b2038732b3f830543fad286c to your computer and use it in GitHub Desktop.
Save hperantunes/14580610b2038732b3f830543fad286c to your computer and use it in GitHub Desktop.
function uniqueReducer(unique, item) {
return unique.includes(item) ? unique : [...unique, item];
}
function mergeObjectsReducer(accumulator, current) {
return {
...accumulator,
...Object.keys(current)
.filter(
key =>
accumulator[key] === undefined ||
(Array.isArray(accumulator[key]) && Array.isArray(current[key])),
)
.reduce(
(object, key) => ({
...object,
[key]: [...(accumulator[key] || []), ...current[key]].reduce(uniqueReducer, []),
}),
{},
),
};
}
var x = [{a: [1,2,3]}, {a: [3,4,5]}, {b: [99]}].reduce(mergeObjectsReducer, {});
console.log(x);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment