【问题标题】:Sorting arrays of objects in this manner, of frequency以这种方式对对象数组进行排序,频率
【发布时间】:2017-05-21 20:13:12
【问题描述】:

我有这种类型的对象数组

students = [
    {
        "name": "Ana Barbique",
        "category":"B"
    }
    {
        "name": "Marko Polo",
        "category":"B"
    }
    {
        "name": "Nick Harper",
        "category":"A"
    }
]

我希望它有一个这种类型的对象数组:

sum = [
    {
        "category": "A",
        "count" : 1
    }
    {
        "category": "B",
        "count" : 2
    }
]

所以基本上我想让对象数组具有出现在学生中的类别及其计数。顺序无关紧要。我以前没有这样做过。

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

首先通过减少students数组创建分类计数对象

const categories = students
   .reduce((cat, student) => (
       cat[student.category]++ || (cat[student.category] = 1), cat
   ), {})

然后遍历类别的键以创建所需的数组

const sum = Object
   .keys(categories)
   .map(name => ({category: name, count: categories[name]}))

【讨论】:

  • Yury - 我试过你的答案并得到 'message': "Uncaught SyntaxError: missing ) after argument list",' 错误。你能编辑你的答案并添加一个有效的 sn-p 吗?
  • 复制时缺少右括号。谢谢。
【解决方案2】:

这是一种纯循环和查找方法。 Yuri Tarabanko 的回答更简洁。

这种方法的关键是使用检查数组对象来保存 sum[] 数组中每个类别的索引。这是一种有用的技术。

var students = [
    {
        "name": "Ana Barbique",
        "category":"B"
    },
    {
        "name": "Marko Polo",
        "category":"B"
    },
    {
        "name": "Nick Harper",
        "category":"A"
    }
]

var sum = [], check = [], obj;
for (var i = 0; i < students.length; i = i + 1) {

  obj = students[i]; 
  if ( check[obj.category] !== undefined ) { 
    // object has already been seen so add to sum array count
    sum[check[obj.category]].count = sum[check[obj.category]].count + 1; 
    
  }
   else {
   // object has not been seen so insert new.
   sum.push({"category": obj.category, "count": 1});
   check[obj.category] = sum.length - 1; // note index of category in sum array.   
   }


}
console.log('sum = ' + JSON.stringify(sum));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 2017-11-24
    • 2019-08-02
    • 2021-07-28
    • 2020-10-19
    相关资源
    最近更新 更多