我正在尝试解决一个简单的问题:给定一个二维整数数组(由整数数组组成的数组)计算整数的总和。
例如,给定这个二维数组:
[
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
输出为 6
。
这是我尝试过的:
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
const twoDsum = a => a.reduce( (r,x) => r + x.reduce( (s,y) => s + y) );
console.log(twoDsum(array));
如你所见,我得到了三个整数,这对我来说是无稽之谈。
我也尝试了以下代码来弄清楚发生了什么,但我不明白
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
// this function works as you can see from the logs
const sum = a => a.reduce( (r,x) => r + x );
for(let i = 0; i < array.length; i++) {
console.log(sum(array[i]));
}
// I don't get why this doesn't
const twoDsum = a => a.reduce( (r,x) => r + sum(x) );
console.log(twoDsum(array));
答案 0 :(得分:5)
确保您明确提供 initialValue
(第二个位置参数)作为 0
以使求和工作。否则将使用第一个元素,即 [1,0,0]
,它将被转换为字符串 1,0,0
:
用作回调第一次调用的第一个参数的值。如果没有提供 initialValue,则数组中的第一个元素将用作初始累加器值
在此处查看工作示例:
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
const twoDsum = a => a.reduce((r, x) => r + x.reduce((s, y) => s + y, 0), 0);
console.log(twoDsum(array));
答案 1 :(得分:2)
我是老派,所以我只会写几个循环。超级容易编码,第一次运行无需调试,我认为这是最容易理解的解决方案:
const twoDsum = matrix => {
let sum = 0;
for( const row of matrix ) {
for( const cell of row ) {
sum += cell;
}
}
return sum;
};
console.log(
twoDsum(
[
[ 1, 0, 0 ],
[ 1, 1, 0 ],
[ 1, 1, 1 ]
]
)
);
答案 2 :(得分:2)
如果您只是想求和,为什么不先将数组展平?
const arr = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
const flatArr = arr.flat()
flatArr
现在应该是 [1, 0, 0, 1, 1, 0, 1, 1, 1]
您现在应该可以使用您希望使用的普通 reduce
const sum = flatArr.reduce((acc, value) => acc += value, 0);
sum
现在应该是 6
答案 3 :(得分:1)
您可以改为使用 .flat()
并使用原始方程。
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
// this function works as you can see from the logs
const sum = a => a.reduce( (r,x) => r + x );
for(let i = 0; i < array.length; i++) {
console.log(sum(array[i]));
}
// I don't get why this doesn't
const twoDsum = a => a.flat().reduce( (r,x) => r + x );
console.log(twoDsum(array));
答案 4 :(得分:1)
我建议不要做两次reduce,而是先使用flat 方法:
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
const twoDsum = a => a.flat().reduce((acc,val) => acc + val);
console.log(twoDsum(array));
答案 5 :(得分:1)
您可以采用递归方法并检查该项目是否为数组。
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string|null
*/
protected $proxies;
答案 6 :(得分:1)
使用 Array.prototype.forEach()
。
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1],
];
const twoDsum = (a) => {
let total = 0;
a.forEach(arr => {
arr.forEach(num => {
total += num;
});
});
return total
};
console.log(twoDsum(array));