user2312612
user2312612

Reputation:

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

Upvotes: 3

Views: 1885

Answers (3)

TheEllis
TheEllis

Reputation: 1736

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386660

You can take an arrray for counting, with an object for the individial count of columns.

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

Upvotes: 1

Regis Portalez
Regis Portalez

Reputation: 4860

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

Upvotes: 0

Related Questions