在Javascript中按多个字段对数组元素进行分组

时间:2017-06-21 05:10:56

标签: javascript arrays

我有以下数组:

var array = [{id: 123, user: "tester", text: ["wow]},
             {id: 123, user: "random", text: ["nice", "cool"]},
             {id: 1245, user: "random", text: ["good"]},
             {id: 1245, user: "tester", text: ["neat"]},
             {id: 123, user: john", text: ["neat", "good", "bye"]},
             {id: 12456, user: "tester", text: ["Bye"]},
             {id: 1245, user: "random", text: ["wow"]},
             {id: 1245, user: "john", text: [{"wow", "nice"]}];

让我们说主要用户是"测试员"其他人都是次要的。我想知道主要用户对每个id有多少文本,以及其他用户对同一个id有多少文本。

因此,数组应返回:

finalArray = [{id: 123, tester: 1, random: 2, john: 3},
              {id: 1245, tester: 1, random: 1, john: 2},
              {id: 12456, tester: 1}]

3 个答案:

答案 0 :(得分:1)

您可以对具有相同id的对象使用哈希表,并将text数组的长度分配给具有用户名称的属性。

此解决方案在哈希表上提供了一个闭包,并使用Array#reduce来获取具有分组结果的新数组。

var array = [{ id: 123, user: "tester", text: ["wow"] }, { id: 123, user: "random", text: ["nice", "cool"] }, { id: 1245, user: "random", text: ["good"] }, { id: 1245, user: "tester", text: ["neat"] }, { id: 123, user: "john", text: ["neat", "good", "bye"] }, { id: 12456, user: "tester", text: ["Bye"] }, { id: 1245, user: "random", text: ["wow"] }, { id: 1245, user: "john", text: ["wow", "nice"] }],
    result = array.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.id]) {
                hash[a.id] = { id: a.id };
                r.push(hash[a.id]);
            }
            hash[a.id][a.user] = a.text.length;
            return r;
        };
    }(Object.create(null)), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

以下是您指定的问题的代码段:

var res = [];
var obj = {};
for(var i in array) {
    if(array[i].user == 'tester') {
        if(obj[array[i].id])
            obj[array[i].id].tester++;
        else 
            obj[array[i].id] = {tester: 1};
    } 
}              
for(var i in array) {
    if(obj[array[i].id] && obj[array[i].user] != 'tester') {
        if(obj[array[i].id][array[i].user])
            obj[array[i].id][array[i].user]++;
        else
            obj[array[i].id][array[i].user] = 1;
    }
}
for(var i in obj) {
   var temp = obj[i];
   temp.id = i;
   res.push(temp);
}
console.log(res);   //output

答案 2 :(得分:0)

你可以使用最新的es6功能map / findIndex来实现这个

检查以下代码段

var arr1 = [{
    id: 123,
    user: "tester",
    text: ["wow"]
  },
  {
    id: 123,
    user: "random",
    text: ["nice", "cool"]
  },
  {
    id: 1245,
    user: "random",
    text: ["good"]
  },
  {
    id: 1245,
    user: "tester",
    text: ["neat"]
  },
  {
    id: 123,
    user: "john",
    text: ["neat", "good", "bye"]
  },
  {
    id: 12456,
    user: "tester",
    text: ["Bye"]
  },
  {
    id: 1245,
    user: "random",
    text: ["wow"]
  },
  {
    id: 1245,
    user: "john",
    text: ["wow", "nice"]
  }
];
let finalResult = [];
arr1.map((item) => {

  const resIdx = findFinal(item.id);
  if (resIdx === -1) {
    const obj = {
      id: `${item.id}`
    }
    const userName = item.user
    obj[userName] = 1;
    finalResult.push(obj)
  } else {
    const resObj = finalResult[resIdx]
    const userName = item.user
    if (resObj.hasOwnProperty(userName)) {
      resObj[userName] += 1;
    } else {
      resObj[userName] = 1;
    }
  }
})
console.log(JSON.stringify(finalResult))

function findFinal(id) {
  return finalResult.findIndex((res) => res.id === id.toString());
}

希望有所帮助