如何从javascript

时间:2018-11-13 11:32:04

标签: 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" }
]

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

[
    { CategoryId: "b5c3f43f941c", count: 2, CategoryColor: "cgreen" }
    { CategoryId: "9872cce5af92", count: 1, CategoryColor: "purple" }
]

在此ID中检查ID是否为相同的显示计数并在新数组中是新的。

希望你明白我想要的。

谢谢

4 个答案:

答案 0 :(得分:3)

使用reduce函数,并在回调内部检查是否存在CategoryId匹配的对象。如果匹配,则更新计数,否则用值创建一个新对象并放入数组

let k = [{
    CategoryId: "b5c3f43f941c",
    CategoryName: "Category 1",
    CategoryColor: "cgreen"
  },
  {
    CategoryId: "9872cce5af92",
    CategoryName: "Category 2",
    CategoryColor: "purple"
  },
  {
    CategoryId: "b5c3f43f941c",
    CategoryName: "Category 1",
    CategoryColor: "cgreen"
  }
]

let result = k.reduce(function(acc, curr) {
  // Check if there exist an object in empty array whose CategoryId matches
  let isElemExist = acc.findIndex(function(item) {
    return item.CategoryId === curr.CategoryId;
  })
  if (isElemExist === -1) {
    let obj = {};
    obj.CategoryId = curr.CategoryId;
    obj.count = 1;
    obj.CategoryColor = curr.CategoryColor;
    acc.push(obj)
  } else {
    acc[isElemExist].count += 1
  }
  return acc;

}, [])

console.log(result)

答案 1 :(得分:3)

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

答案 2 :(得分:0)

const array_unique = require('array-hyper-unique').array_unique

let arr = [
  { CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
  { CategoryId: "9872cce5af92", CategoryName: "Category 2", CategoryColor: "purple" }
  { CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
]

array_unique(arr).length

答案 3 :(得分:0)

您可以先sort数组,然后计算重复项。缺点是,由于排序,它将修改原始的yourArray,因此请谨慎使用。

yourArray.sort((a, b) => {
  if (a.CategoryName > b.CategoryName) {
    return 1;
  }
  if (a.CategoryName < b.CategoryName) {
    return -1;
  }
  return 0;
});

var pivot = yourArray[0];
pivot.count = 0;
var counted = [pivot];
yourArray.forEach(item => {
  if (item.CategoryId === pivot.CategoryId) {
    pivot.count++;
  } else {
    pivot = item;
    pivot.count = 1;
    counted.push(pivot);
  }
});