gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:35 27 4
gpt4 key购买 nike

我有一个数组如下

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}];

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

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

我尝试按如下方式使用分组

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);

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

最佳答案

您确实可以使用以位置为键的 map ,但随后将普通对象作为值。您的代码中的问题是您将项目插入一个数组,而不是将月份值转换为单个对象(每个位置)的属性。

因此,给定一个包含普通对象的 map ,迭代输入并将月份属性注入(inject)那些普通对象,以及相应的百分比值,然后获取该 map 的值:

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);

关于javascript - 如何在 JavaScript/Jquery 中按数组分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54856900/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com