From 54cdaa6951ac3b888e886e03f2e5f4301950799f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 4 Oct 2020 00:26:51 +0300 Subject: [PATCH] Add combine --- snippets/combine.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 snippets/combine.md diff --git a/snippets/combine.md b/snippets/combine.md new file mode 100644 index 000000000..03e0d8357 --- /dev/null +++ b/snippets/combine.md @@ -0,0 +1,40 @@ +--- +title: combine +tags: array,object,intermediate +--- + +Combines two arrays of objects, using the specified key to match objects. + +- Use `Array.protoype.reduce()` with an object accumulator to combine all objects in both arrays based on the given `prop`. +- Use `Object.values()` to convert the resulting object to an array and return it. + +```js +const combine = (a, b, prop) => + Object.values( + [...a, ...b].reduce((acc, v) => { + if (v[prop]) + acc[v[prop]] = acc[v[prop]] + ? { ...acc[v[prop]], ...v } + : { ...v }; + return acc; + }, {}) + ); +``` + +```js +const x = [ + { id: 1, name: 'John' }, + { id: 2, name: 'Maria' } +]; +const y = [ + { id: 1, age: 28 }, + { id: 3, age: 26 }, + { age: 3} +]; +combine(x, y, 'id'); +// [ +// { id: 1, name: 'John', age: 28 }, +// { id: 2, name: 'Maria' }, +// { id: 3, age: 26 } +// ] +```