From a67ff4f407107f7577fa1a166581137a3ce862cb Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Thu, 1 Oct 2020 15:05:06 +1000 Subject: [PATCH] Added keyBy and groupBy helpers --- src/helpers/shared.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/helpers/shared.js b/src/helpers/shared.js index 68277f9..2172c66 100644 --- a/src/helpers/shared.js +++ b/src/helpers/shared.js @@ -54,3 +54,18 @@ export function logImage(url, width, height) { export function isEmpty(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object; } + +export function keyBy(array, key) { + return array.reduce( + (prev, current) => ({ ...prev, [key ? current[key] : current]: current }), + {} + ); +} + +export function groupBy(array, key) { + return array.reduce((prev, current) => { + const k = current[key]; + (prev[k] || (prev[k] = [])).push(current); + return prev; + }, {}); +}