计算javascript中每个值的出现次数

计算javascript中每个值的出现次数

我以繁琐的循环结束转换

[{Name: "Daniel Montes", color: "red"},
 {Name: "Daniel Montes", color: "red"},
 {Name: "Daniel Montes", color: "red"},
 {Name: "Michelle Aguirre", color: "red"},
 {Name: "Daniel Montes", color: "green"}
]




[
{Name: "Daniel Montes", green:1,red:3},
{Name: "Michelle Aguirre", green:0,red:1},
]


红色和绿色只有2种颜色,因此也可以进行硬编码。

最好的方法是什么?
我们在lodash上有东西吗?

最佳答案

var input = [{Name: "Daniel Montes", color: "red"},
{Name: "Daniel Montes", color: "red"},
{Name: "Daniel Montes", color: "red"},
{Name: "Michelle Aguirre", color: "red"},
{Name: "Daniel Montes", color: "green"}
];

function solve(list){
    var map = new Map();
    var entry = null;
    for(var item of list){
        if(!map.has(item.Name))
            map.set(item.Name, {Name: item.Name});

        entry = map.get(item.Name);

        if(entry.hasOwnProperty(item.color))
            entry[item.color] = entry[item.color] + 1;
        else
            entry[item.color] = 1;
    }
    return Array.from(map.values());
}

console.log(solve(input))





这是我为您的问题写的一个快速解决方案。

关于javascript - 计算javascript中每个值的出现次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48291972/

10-09 22:41