JS。循环遍历多维数组以计算每列中元素的出现次数

时间:2016-05-12 14:40:25

标签: javascript object multidimensional-array

我想按列计算每个元素的出现次数。我的下面的代码计算第一列,生成{"dem":1,"rep":1,"ind":3}因为有1个dem,1个代表&第3栏中的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 个答案:

答案 0 :(得分:2)

您可以使用arrray进行计数,并使用一个对象进行单独的列计数。

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>');

答案 1 :(得分:1)

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

&#13;
&#13;
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)));
&#13;
&#13;
&#13;

答案 2 :(得分: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)))