a1tern4tive
a1tern4tive

Reputation: 422

JavaScript: Iterate through multidimentional array vertically

I've got multidimentional array and I need to count chars vertically. No problem to count in row, but I can't iterate it like vertically. Tip please.

const arrayData = [
  ['a', 'b', 'c'],
  ['a', 'f', 'g'],
  ['b']
];

My code looks like this:

  const countChars = (input, direction) => {
    if (direction === 'row') {
      return input.reduce((acc, curr) => {
        acc[curr] = acc[curr] ? ++acc[curr] : 1;
        return acc;
      }, {});
    }

    if (direction === 'column') {
      for (let row = 0; row < input.length; row++) {
        for (let column = 0; column < input[row].length; column++) {
          console.log(input[column][row]);
        }
        console.log('---');
      }
    }
  }

But for columns I'm getting this as result:

a
a
b
---
b
f
undefined
---
c

So I'm losing there a char because of undefined.

The result should be like for columns:

{ 'a': 2, 'b': 1 }
{ 'b': 1, 'f': 1 }
{ 'c': 1, 'g': 1 }

Upvotes: 2

Views: 686

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386660

You could iterate the array and collect same values at same index.

const
    array = [['a', 'b', 'c'], ['a', 'f', 'g'], ['b']],
    result = array.reduce((r, a) => {
        a.forEach((v, i) => {
            r[i] = r[i] || {};
            r[i][v] = (r[i][v] || 0) + 1;
        });
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions