对数组中的项进行分类

时间:2018-06-13 15:15:29

标签: javascript

我有这两个数组(i)一个类别数组(ii)一个帖子类别数组

   let category = [{ "total":"0", "value": "technology", "name": "Technology"},
    { "total":"0", "value": "sport", "name": "Sport"},
    { "total":"0", "value": "movie", "name": "Movie"},
    { "total":"0", "value": "music", "name": "Music"},
    { "total":"0", "value": "general", "name": "General"}]

和类别数组获取类似于此

 let post = [ "category" : "sport", "category" : "music", "category" :  "general", 
    "category" : "music", "category" : "movie", "category" : "sport", 
    "category" : "technology", "category" : "sport"]

我一直在尝试不同系列的模式来计算每个类别的出现次数。这些是我试图解决的问题。

category.map((cat) => {
  post.reduce((cat, pro) => {
    if(cat.value === pro) return cat.total + 1;
   },0)
});

2 个答案:

答案 0 :(得分:2)

您可以使用reduce汇总/计算帖子数组。使用forEach更新类别总计

let post = [{"category":"sport"},{"category":"music"},{"category":"general"},{"category":"music"},{"category":"movie"},{"category":"sport"},{"category":"technology"},{"category":"sport"}]
let category = [{"total":"0","value":"technology","name":"Technology"},{"total":"0","value":"sport","name":"Sport"},{"total":"0","value":"movie","name":"Movie"},{"total":"0","value":"music","name":"Music"},{"total":"0","value":"general","name":"General"}]

//Sumarize/count post array
let count = post.reduce((c, {category}) => {
  c[category] = (c[category] || 0) + 1;
  return c;
}, {});

//Update category
category.forEach(o => {
  o.total = count[o.value] || 0;
});

console.log(category);

答案 1 :(得分:0)

您必须使用对象方法

  

var a = [" abc"]也用于初始化数组,其格式为var a = [" a"]

在您的情况下,您必须使用

的对象声明
  

用花括号示例var a = {" name":" xyz"}