如何在 JavaScript/Jquery 中按数组分组

Dev*_*vTN 5 javascript jquery

我有一个如下所示的数组

array1 = [{"month":"January","location":"CENTRAL","percentage":94},
{"month":"February","location":"CENTRAL","percentage":97},
{"month":"March","location":"CENTRAL","percentage":93},
{"month":"January","location":"NORTH","percentage":95},
{"month":"February","location":"NORTH","percentage":91},
{"month":"March","location":"NORTH","percentage":98}];
Run Code Online (Sandbox Code Playgroud)

我想格式化我的数组,如下所示

array2= [{
    location: "CENTRAL",
    January: 94,
    February: 97,
    March: 93},
    {
    location: "NORTH",
    January: 95,
    February: 91,
    March: 98}];
Run Code Online (Sandbox Code Playgroud)

我尝试使用按功能分组,如下所示

function groupBy(list, keyGetter) {
    const map = new Map();
    list.forEach((item) => {
        const key = keyGetter(item);
        if (!map.has(key)) {
            map.set(key, [item]);
        } else {
            map.get(key).push(item);
        }
    });
    return map;
}

const grouped = groupBy(array1, arr => arr.location);
console.log(grouped);
Run Code Online (Sandbox Code Playgroud)

但我没有得到相同的格式。有什么建议请我的想法中缺少什么?非常感谢。

tri*_*cot 3

您确实可以使用按位置键控的地图,但随后使用普通对象作为值。代码中的问题是您将项目推送到 array 中并且没有将月份值转换为单个对象(每个位置)的属性。

因此,给定一个包含普通对象的映射,迭代输入并将月份属性与相应的百分比值一起注入到这些普通对象中,然后获取该映射的值:

const array1 = [{"month":"January","location":"CENTRAL","percentage":94},{"month":"February","location":"CENTRAL","percentage":97},{"month":"March","location":"CENTRAL","percentage":93},{"month":"January","location":"NORTH","percentage":95},{"month":"February","location":"NORTH","percentage":91},{"month":"March","location":"NORTH","percentage":98}];

const map = new Map(array1.map(({location}) => [location, { location }]));
array1.forEach(o => map.get(o.location)[o.month] = o.percentage);
const result = [...map.values()];

console.log(result);
Run Code Online (Sandbox Code Playgroud)