Files
threshold-ui/ui/desktop/app/helpers/group-by.js
T
hashicorp-copywrite[bot]andCameron Perera 3d610427d0 [COMPLIANCE] Add Copyright and License Headers (#1617)
* [COMPLIANCE] Add Copyright and License Headers

* chore: 🤖 update Copyright headers to satisfy our lint rules

---------

Co-authored-by: hashicorp-copywrite[bot] <110428419+hashicorp-copywrite[bot]@users.noreply.github.com>
Co-authored-by: Cameron Perera <cameron.perera@hashicorp.com>
2023-03-01 09:39:41 -06:00

30 lines
907 B
JavaScript

/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*/
import { helper } from '@ember/component/helper';
const groupByReducer = (items, key) => {
const obj = items.reduce((result, item) => {
if (!result[item[key]]) result[item[key]] = { key: item[key], items: [] };
result[item[key]].items.push(item);
return result;
}, {});
// Convert object group to an array for iteration
const arr = Object.keys(obj).map((key) => obj[key]);
return arr;
};
/**
* This helper accepts an array of objects and groups them by a specified key.
* It returns a new array of objects in the form [{ key, items }], where `key`
* is the value of the specified key and `items` is an array of matching items.
* @param {object[]} items
* @param {string} key
*/
export default helper(function groupBy([items, key]) {
const result = groupByReducer(items, key);
return result;
});