mattnewbie mattnewbie - 6 months ago 61
Javascript Question

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

Answer

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