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

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

本文关键字:元素 JS 遍历 数组 循环      更新时间:2023-09-26

我想按列计算每个元素的出现次数。我下面的代码计算第一列,产生{"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)));

您可以使用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>');

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

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

这并不是一个完美的解决方案,但您可以很容易地将已经完成的工作扩展为只在循环中运行

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