使用Lodash用两个条件对总数进行计数

编程入门 行业动态 更新时间:2024-10-26 14:31:58
本文介绍了使用Lodash用两个条件对总数进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不知道如何根据位置和唯一的序列号对设备总数进行计数.

I can't figure out how I can count the total devices based on location and unique serial number.

{ "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" } ] } ]

}

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

I would like to capture the total number of unique devices per location

Chicago - 4 New York - 3

推荐答案

在这里,它是使用lodash链接语法的单个表达式.简短的版本是将所有设备归为一个庞大的列表,然后按位置对它们进行分组,然后针对每个位置消除重复的ID,然后对设备进行计数.

Here it is, in a single expression with lodash chaining syntax. The short version is you get all devices into one massive list, then you group them by location, then for each location eliminate the duplicate ids, then count the devices.

_(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},尽管您显然可以添加另一个语句以字符串形式将其打印出来.

The final result is an object of the form: {"New York": 1, "NewYork": 3, "Chicago": 4}, though you could add another statement to print that out in string form, obviously.

我鼓励您逐步执行此步骤,以查看每个步骤的结果并了解其作用.

I'd encourage you to run through this step-by-step to see the result of each step and understand what it's doing.

更多推荐

使用Lodash用两个条件对总数进行计数

本文发布于:2023-10-30 12:09:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总数   条件   两个   Lodash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!