简体   繁体   English

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

[英]JS. Loop through multidimensional array to count occurrences of elements in each column

I would like to count the occurrences of each element by column. 我想按列计算每个元素的出现次数。 My code below counts the first column, producing {"dem":1,"rep":1,"ind":3} As there are 1 dem, 1 rep & 3 ind in the first column. 我的下面的代码计算第一列,生成{"dem":1,"rep":1,"ind":3}因为第一列中有1个dem,1个rep和3个ind。 I would like to extend my code below, so that I end up with an object (like above) for each column, not just for one column. 我想在下面扩展我的代码,这样我最终会得到每个列的对象(如上所述),而不仅仅是一列。

How can I do this please? 我该怎么办?

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

You can take an arrray for counting, with an object for the individial count of columns. 您可以使用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>'); 

You just need another loop to iterate on columns: 您只需要另一个循环来迭代列:

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

This isn't exactly an elegant solution, but you could easily extend what you have already done to just run in a loop 这不是一个优雅的解决方案,但您可以轻松地扩展您已经完成的操作,只需循环运行即可

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM