如何从JavaScript中的数组对象中计数唯一值 [英] How to count unique value from object of array in javascript
本文介绍了如何从JavaScript中的数组对象中计数唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算唯一值的数量并将其放入新数组中. 我有下面的数组:
I want to calculate number of unique value and put that in new array. I have below array:
[
{ CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
{ CategoryId: "9872cce5af92", CategoryName: "Category 2", CategoryColor: "purple" }
{ CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
]
我想要具有以下结果的新数组:
I want new array with below result:
[
{ CategoryId: "b5c3f43f941c", count: 2, CategoryColor: "cgreen" }
{ CategoryId: "9872cce5af92", count: 1, CategoryColor: "purple" }
]
在此ID中检查ID是否为相同的显示计数并在新数组中是新的.
In this check by id, if id is same show count and new in new array.
希望你能理解我想要的东西.
Hope you understand what I want.
谢谢
推荐答案
您可以使用"for..of"遍历数组,并创建一个临时对象以在每次循环中保存数据.如果tempObject中存在相同的ID,则将计数加1
You can loop through array using "for..of" and create a temporary object to save data in every loop. If same id exists in tempObject then increment count by 1
var arr = [
{ CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
, { CategoryId: "9872cce5af92", CategoryName: "Category 2", CategoryColor: "purple" }
, { CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
]
var tempResult = {}
for(let { CategoryColor, CategoryId } of arr)
tempResult[CategoryId] = {
CategoryId,
CategoryColor,
count: tempResult[CategoryId] ? tempResult[CategoryId].count + 1 : 1
}
let result = Object.values(tempResult)
console.log(result)
这篇关于如何从JavaScript中的数组对象中计数唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文