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 }