JS. 遍历多维数组以计算每列元素出现的次数

3
我想要按列计算每个元素的出现次数。下面的代码计算第一列,得到结果 {"dem":1,"rep":1,"ind":3} 因为在第一列中有 1 个 dem、1 个 rep 和 3 个 ind。我想要修改下面的代码,使我可以获得多个列的对象(如上所示),而不仅是一个列。
请问我该怎么做?
voters =
         [["dem", "ind", "rep"],
          ["rep", "ind", "dem"],
          ["ind", "dem", "rep"],
           ["ind", "dem", "rep"],
          ["ind", "rep", "dem"]];


 var columnArr = voters.map(function(row) {
  return row[0];
}); 

count = {}
columnArr.forEach(function(el){
    count[el] = count[el] + 1 || 1
});

  document.write( (JSON.stringify(count)));
3个回答

1
您可以使用数组进行计数,使用对象来记录每列的个别计数。

var voters = [["dem", "ind", "rep"], ["rep", "ind", "dem"], ["ind", "dem", "rep"], ["ind", "dem", "rep"], ["ind", "rep", "dem"]],
    count = [];

voters.forEach(function (a) {
    a.forEach(function (b, i) {
        count[i] = count[i] || {};
        count[i][b] = (count[i][b] || 0) + 1;
    });
});

document.write('<pre>' + JSON.stringify(count, 0, 4) + '</pre>');


0
你只需要另一个循环来迭代列:

voters = [
  ["dem", "ind", "rep"],
  ["rep", "ind", "dem"],
  ["ind", "dem", "rep"],
  ["ind", "dem", "rep"],
  ["ind", "rep", "dem"]
];


count = {}


for (var colIndex = 0; colIndex < voters[0].length; ++colIndex) {
  var columnArr = voters.map(function(row) {
    return row[colIndex];
  });
  
  console.log(columnArr);

  count[colIndex] = {};
  columnArr.forEach(function(el) {
      count[colIndex][el] = count[colIndex][el] ? count[colIndex][el] + 1 : 1;
  });
}

document.write((JSON.stringify(count)));


0

这并不是一个十分优雅的解决方案,但你可以很容易地扩展你已经完成的内容,使其在一个循环中运行。

voters = [
  ["dem", "ind", "rep"],
  ["rep", "ind", "dem"],
  ["ind", "dem", "rep"],
  ["ind", "rep", "dem"]
];

var colCounts = [];

function countUsagesByColumn(numCols) {
  var columnArr;
  var count;
  for (var i = 0; i < numCols; i++) {
    columnArr = voters.map(function(row) {
      return row[i];
    });

    count = {}
    columnArr.forEach(function(el) {
      count[el] = count[el] + 1 || 1
    });
    console.log(count);
    colCounts.push(count);
  }
}

countUsagesByColumn(3);

document.write((JSON.stringify(colCounts)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接