From 0bfc37790c286c4a8a979a6ace15171340d45be5 Mon Sep 17 00:00:00 2001 From: Tor Andersson Date: Thu, 14 Mar 2024 17:18:39 +0100 Subject: Add Object.groupBy implementation to common utils. --- public/common/util.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'public') diff --git a/public/common/util.js b/public/common/util.js index 75cd824..0979178 100644 --- a/public/common/util.js +++ b/public/common/util.js @@ -304,3 +304,26 @@ function object_diff(a, b) { } return true } + +// same as Object.groupBy +function object_group_by(items, callback) { + let groups = {} + if (typeof callback === "function") { + for (let item of items) { + let key = callback(item) + if (key in groups) + groups[key].push(item) + else + groups[key] = [ item ] + } + } else { + for (let item of items) { + let key = item[callback] + if (key in groups) + groups[key].push(item) + else + groups[key] = [ item ] + } + } + return groups +} -- cgit v1.2.3