简体   繁体   中英

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

While the code below will satisfy adding two arrays with different lengths, how can I modify this to accept an arbitrary number of arrays as arguments so that, for example, ([1, 2, 3], [4, 5], [6]) will return an array of [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
}

Use a nested array, and loop over the array rather than hard-coding two array variables.

You can use arrays.map() to get all the lengths so you can calculate the maximum length. And arrays.reduce() to sum up an element in each array.

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

Instead of using a for loop that requires you to know the lengths of each array, try using something that doesn't. For example - while loop.

Increment using a dummy variable and reset it for each array and set condition for loop termination as - arr[i] === null .

You can use arguments object inside function.

arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function.

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

Solution:

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

Output:[ 11, 7, 3 ]

Use rest param syntax to accept an arbitrary number of arguments. Sort the outer array by their length in descending order. By using destructuring assignment separate the first and rest of the inner arrays. At last use Array.prototype.map() to traverse the first array as it is the largest array and use Array.prototype.reduce() method to get the summation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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