计算 JavaScript 中二维数组的总和

Computing sum of a 2D array in JavaScript

我正在尝试解决一个简单的问题:给定一个二维整数数组(一个由整数数组组成的数组)计算整数之和。
例如,给定此二维数组:

[
[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));

确保将 initialValue(第二个位置参数)显式提供为 0 以使求和有效。否则将使用第一个元素,即 [1,0,0],它将被转换为字符串 1,0,0:

A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value

在此处查看工作示例:

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

您可以改用 .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));

我是守旧派,所以我只想写几个循环。超级容易编写代码,无需调试即可首次运行,我认为这是最容易理解的解决方案:

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 ]
        ]
    )
);

我建议不要做两次 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));

您可以采用递归方法检查项目是否为数组。

const
   addArray = (s, v) => s + (Array.isArray(v) ? v.reduce(addArray, 0) : v),
   data = [[1, 0, 0], [1, 1, 0], [1, 1, 1]],
   sum = data.reduce(addArray, 0);

console.log(sum);

如果您只是想求和,那为什么不先展平数组呢?

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

使用 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));