【问题标题】:Array of objects: Count occurrences of a unique property in JavaScript [duplicate]对象数组:计算 JavaScript 中唯一属性的出现次数 [重复]
【发布时间】:2022-01-11 23:15:06
【问题描述】:

给定一个示例 JSON 对象数组,像这样......

[
  {
    "firstName": "Bob",
    "lastName": "Smith",
    "city": "Preston",
    "st": "Florida",
    "age": 15
  },
  {
    "firstName": "Tom",
    "lastName": "Jones",
    "city": "Springfield",
    "st": "Illinois",
    "age": 34
  },
  {
    "firstName": "Mary",
    "lastName": "Hart",
    "city": "Miami",
    "st": "Florida",
    "age": 22
  },
  {
    "firstName": "Jenny",
    "lastName": "Dixon",
    "city": "Palm City",
    "st": "Florida",
    "age": 26
  }
]

根据特定属性的分组获取出现次数的最佳方法是什么?所以,假设我想生成一个 JSON 对象,它具有每个唯一状态(“st”)和出现次数......

[
  {
    "st": "Illinois",
    "count": 1
  },
  {
    "st": "Florida",
    "count": 3
  }
]

我可以使用 for-let 手动完成,循环遍历数组,在循环时跟踪值等。但我确信使用 ES6 有更有效的方法。你能帮帮我吗?谢谢。

【问题讨论】:

  • Object.entries(data.reduce((o, d) => ({...o, [d.st]: (o[d.st] || 0) + 1 }), {})).map(([st,count]) => ({ st, count }))
  • const results = Object.values(data.reduce((obj, item) => { obj[item.st] = obj[item.st] = { st: item.st : count: 0 }; obj[item.st].count++; return obj }, {}));

标签: javascript arrays ecmascript-6


【解决方案1】:

您可以使用Array#reduce 进行计数

let counts = json.reduce((b, a) => {
  let index = b.findIndex(j => j.st === a.st);
  if (index > -1) b[index].count++;
  else b.push({st: a.st, count: 1});
  return b;
}, [])

#UPDATE:正如@epascarello 所提到的,有一种更有效的方法来解决这个问题,删除findIndex 循环并使用Object.values

const results = Object.values(json.reduce((obj, item) => {
   obj[item.st] = obj[item.st] || { st: item.st, count: 0 };
   obj[item.st].count++;       
   return obj;}, {}))

let json = [{
    "firstName": "Bob",
    "lastName": "Smith",
    "city": "Preston",
    "st": "Florida",
    "age": 15
  },
  {
    "firstName": "Tom",
    "lastName": "Jones",
    "city": "Springfield",
    "st": "Illinois",
    "age": 34
  },
  {
    "firstName": "Mary",
    "lastName": "Hart",
    "city": "Miami",
    "st": "Florida",
    "age": 22
  },
  {
    "firstName": "Jenny",
    "lastName": "Dixon",
    "city": "Palm City",
    "st": "Florida",
    "age": 26
  }
]

let counts = json.reduce((b, a) => {
  let index = b.findIndex(j => j.st === a.st);
  if (index > -1) b[index].count++;
  else b.push({st: a.st, count: 1});
  return b;
}, [])

console.log(counts)

const results = Object.values(json.reduce((obj, item) => {
obj[item.st] = obj[item.st] || { st: item.st, count: 0 };
obj[item.st].count++;       
return obj;}, {}))

console.log(results)

【讨论】:

  • 使用 findIndex 有点低效
  • const results = Object.values(data.reduce((obj, item) => { obj[item.st] = obj[item.st] = { st: item.st : count: 0 }; obj[item.st].count++; return obj }, {})); 会是更好的方法,这样您就不会不断循环遍历数组来查找索引
  • 谢谢@epascarello - 你的代码的一个小模块,我将它添加到答案中。干杯!
猜你喜欢
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多