2

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 }
2
  • 2
    please add the code you tried and the wanted result. Commented Jun 9, 2020 at 6:34
  • @NinaScholz edited Commented Jun 9, 2020 at 6:38

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.