繁体   English   中英

如何在Javascript中对任意数量的不同长度数组的元素求和?

[英]How do I sum the elements of an arbitrary number of arrays with different lengths in Javascript?

虽然下面的代码将满足添加两个不同长度的数组,但我如何修改它以接受任意数量的数组作为参数,例如 ([1, 2, 3], [4, 5], [6 ]) 将返回一个 [11, 7, 3] 的数组?

const addTogether = (arr1, arr2) => {
  let result = [];
  for (let i = 0; i < Math.max(arr1.length, arr2.length); i++) {
    result.push((arr1[i] || 0) + (arr2[i] || 0))

  }
  return result
}

使用嵌套数组,并循环遍历数组而不是硬编码两个数组变量。

您可以使用arrays.map()获取所有长度,以便计算最大长度。 arrays.reduce()总结每个数组中的一个元素。

 const addTogether = (...arrays) => { let result = []; let len = Math.max(...arrays.map(a => a.length)); for (let i = 0; i < len; i++) { result.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0)); } return result } console.log(addTogether([1, 2, 3], [4, 5], [6]));

与其使用要求您知道每个数组长度的for循环,不如尝试使用不知道的东西。 例如 - while循环。

使用虚拟变量递增并为每个数组重置它,并将循环终止的条件设置为 - arr[i] === null

您可以在函数内使用参数对象。

arguments是一个可在函数内部访问的类数组对象,其中包含传递给该函数的参数的值。

 const addTogether = function () { const inputs = [...arguments]; const maxLen = Math.max(...inputs.map((item) => item.length)); const result = []; for (let i = 0; i < maxLen; i ++) { result.push(inputs.reduce((acc, cur) => acc + (cur[i] || 0), 0)); } return result; }; console.log(addTogether([1,2,3], [4,5], [6]));

解决方案:

 const addTogether = (...args) => { let result = []; let max = 0; args.forEach((arg)=>{ max = Math.max(max,arg.length) }) for(let j=0;j<max;j++){ result[j]= 0 for (let i = 0; i < args.length; i++) { if(args[i][j]) result[j]+= args[i][j] } } return result } console.log(addTogether([1, 2, 3], [4, 5], [6]))

输出:[ 11, 7, 3 ]

使用rest param syntax接受任意数量的参数。 按长度降序对外部数组进行排序。 通过使用解构赋值将内部数组的第一个和其余部分分开。 最后使用Array.prototype.map()遍历第一个数组,因为它是最大的数组,并使用Array.prototype.reduce()方法求和。

 const addTogether = (...ar) => { ar.sort((x, y) => y.length - x.length); const [first, ...br] = ar; return first.map( (x, i) => x + br.reduce((p, c) => (i < c.length ? c[i] + p : p), 0) ); }; console.log(addTogether([1, 2, 3], [4, 5], [6]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM