generated from laxmanpokhrel/xmanscript-npm-package-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
32 lines (30 loc) · 1.23 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* eslint-disable no-continue */
/* eslint-disable no-restricted-syntax */
/**
* The function `groupArrayOfObjectsByValueOfAKey` takes an array of objects and a key, and groups the
* objects based on the similarity of their values for that key.
* @param {Record<string, any>[]} arr - An array of objects. Each object in the array has properties
* with key-value pairs.
* @param {string} key - The `key` parameter is a string that represents the key in each object of the
* `arr` array that will be used to group the objects.
* @returns The function `groupArrayOfObjectsByValueOfAKey` returns an array of arrays. Each inner array
* contains objects from the input array `arr` that have the same value for the specified `key`.
*/
export default function groupArrayOfObjectsByValueOfAKey(
arr: Record<string, any>[],
key: string
): Record<string, any>[][] {
const groupedArrays: { [key: string]: Record<string, any>[] } = {};
for (const obj of arr) {
const keyValue = obj[key];
if (keyValue === undefined || keyValue === null) {
continue;
}
if (!groupedArrays[keyValue]) {
groupedArrays[keyValue] = [obj];
} else {
groupedArrays[keyValue].push(obj);
}
}
return Object.values(groupedArrays);
}