我无法弄清楚如何根据位置和唯一的序列号对设备总数进行计数。
{
"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
最佳答案
它是在具有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
最终结果是以下形式的对象:{“ New York”:1,“ NewYork”:3,“ Chicago”:4},尽管您显然可以添加另一个语句以字符串形式将其打印出来。
我鼓励您逐步执行此步骤,以查看每个步骤的结果并了解其工作情况。
关于javascript - 使用Lodash用两个条件对总数进行计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25677207/