Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:垂直遍历多维数组_Javascript_Arrays_Loops_Multidimensional Array_Count - Fatal编程技术网

JavaScript:垂直遍历多维数组

JavaScript:垂直遍历多维数组,javascript,arrays,loops,multidimensional-array,count,Javascript,Arrays,Loops,Multidimensional Array,Count,我有多维数组,我需要垂直计数字符。在行中计数没有问题,但我不能像垂直方向那样迭代它。请给小费 const arrayData = [ ['a', 'b', 'c'], ['a', 'f', 'g'], ['b'] ]; 我的代码如下所示: const countChars = (input, direction) => { if (direction === 'row') { return input.reduce((acc, curr) =>

我有多维数组,我需要垂直计数字符。在行中计数没有问题,但我不能像垂直方向那样迭代它。请给小费

const arrayData = [
  ['a', 'b', 'c'],
  ['a', 'f', 'g'],
  ['b']
];
我的代码如下所示:

  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('---');
      }
    }
  }
因为未定义,所以我丢失了一个字符

列的结果应类似于:

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

您可以迭代数组并在同一索引中收集相同的值

const
数组=['a'、[b'、[c']、[a'、[f'、[g']、[b'],
结果=数组。减少((r,a)=>{
a、 forEach((v,i)=>{
r[i]=r[i]|{};
r[i][v]=(r[i][v]| | 0)+1;
});
返回r;
}, []);
控制台日志(结果)

。作为控制台包装{max height:100%!important;top:0;}
请添加您尝试的代码和想要的结果。@NinaScholz
{ 'a': 2, 'b': 1 }
{ 'b': 1, 'f': 1 }
{ 'c': 1, 'g': 1 }