如何从javascript中的数组对象中计算唯一值

roh*_*807 3 javascript arrays array-push

我想计算唯一值的数量并将其放入新数组中。我有以下数组:

[
  { CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
  { CategoryId: "9872cce5af92", CategoryName: "Category 2", CategoryColor: "purple" }
  { CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
]
Run Code Online (Sandbox Code Playgroud)

我想要具有以下结果的新数组:

[
    { CategoryId: "b5c3f43f941c", count: 2, CategoryColor: "cgreen" }
    { CategoryId: "9872cce5af92", count: 1, CategoryColor: "purple" }
]
Run Code Online (Sandbox Code Playgroud)

在这个通过 id 的检查中,如果 id 是相同的,则在新数组中显示计数和新的。

希望你明白我想要什么。

谢谢,

Nit*_*ang 7

您可以使用“for..of”循环遍历数组并创建一个临时对象以在每个循环中保存数据。如果 tempObject 中存在相同的 id,则将 count 增加 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)
Run Code Online (Sandbox Code Playgroud)