计数使用Lodash 2条规定 - 总(Count total with two criterias

2019-10-20 21:10发布

我想不通我怎么能算基于地理位置和独特的序列号,总的设备。

{
"dates": [
    {
        "date": "Sep 1, 2014",
        "devices": [
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "abc123"
            },
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "xyz456"
            },
            {
                "model": "HP",
                "location": "New York",
                "serialNum": "123456"
            },
            {
                "model": "Brother",
                "location": "Chicago",
                "serialNum": "DEF777"
            }
        ]
    },
    {
        "date": "Sep 2, 2014",
        "devices": [
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "abc123"
            },
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "xyz456"
            }
        ]
    },
    {
        "date": "Sep 3, 2014",
        "devices": [
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "xyz456"
            },
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "stu789"
            },
            {
                "model": "Epson",
                "location": "NewYork",
                "serialNum": "123456"
            },
            {
                "model": "Epson",
                "location": "NewYork",
                "serialNum": "555555"
            },
            {
                "model": "HP",
                "location": "NewYork",
                "serialNum": "987654"
            }
        ]
    }
]

}

我想捕捉每个位置的唯一设备总数

Chicago - 4
New York - 3

Answer 1:

这是,在具有lodash链接语法的单个表达式。 简短的版本是,你通过位置获取所有设备整合到一个庞大的列表中,那么你将它们分组,然后为每个位置消除重复的ID,然后计算设备。

_(dates) //Begin chain
    .pluck("devices") //get the device list for each date
    .flatten() //combine all device lists into a master list
    .groupBy("location") //group into an object of {"location": [devices]} pairs
    .mapValues(function (devicesForLocation) { //replaces [devices] with a count of number of unique serial numbers
        return _(devicesForLocation) //Begin chain
            .pluck("serialNum") //get the serial number for each device
            .uniq() //remove the duplicate serial numbers
        .value() //End chain
        .length; // get the count of unique serial numbers
    }) // result is an object of {"location": countOfUniqueDevices} pairs
.value() //End chain

最终的结果是形式的对象:{“纽约”:1,“纽约”:3,“芝加哥”:4},尽管你可以添加其他的语句,以打印出字符串形式,效果显着。

我鼓励你通过这一步一步运行,看看每一步的结果,明白它在做什么。



文章来源: Count total with two criterias using Lodash