最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to calculate the sum of multiple arrays? - Stack Overflow

matteradmin1PV0评论

I am trying to solve an equation where I add numbers from a list of arrays following the indices.

Each array of a list are a randomly generated fixed-length array of 4 numbers like so:

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

So what I am trying to do is get the sum of each number of each index from each array. Like so:

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

// expectedResult = [8, 19, 18, 7];

How can I achieve this?

I am trying to solve an equation where I add numbers from a list of arrays following the indices.

Each array of a list are a randomly generated fixed-length array of 4 numbers like so:

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

So what I am trying to do is get the sum of each number of each index from each array. Like so:

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

// expectedResult = [8, 19, 18, 7];

How can I achieve this?

Share Improve this question edited Feb 15, 2019 at 16:03 yqlim 7,1183 gold badges20 silver badges44 bronze badges asked Feb 15, 2019 at 15:51 Haris SpahijaHaris Spahija 831 silver badge8 bronze badges 1
  • 3 What have you tried though? – Jonas Wilms Commented Feb 15, 2019 at 15:54
Add a ment  | 

6 Answers 6

Reset to default 7

This is another approach that uses map() over the first array, nested with a reduce() that generated the total of the corresponding column.

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
];

const sums = list[0].map((x, idx) => list.reduce((sum, curr) => sum + curr[idx], 0));

console.log(sums);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1],
];

const result = list.reduce((a, b) => a.map((c, i) => c + b[i]));

console.log(result);

Update: an explanation was asked for.

First of all reduce will given an array (of arrays) and want to reduce it down to single value (an array). To do this it will call the first arrow function 2 times. The first time a will be [2,9,1,2] and b will be [2,3,9,4]. With a and b the first arrow function will return a map of a. With a being an array it will return an array where each element is added to the corresponding element of array b. The result of this first map will be [4,12,10,6]. reduce will now call the first arrow function a second time with a (the first map result) [4,12,10,6] and b (the final array element of the input [4,7,8,1]). This arrow function will do the same thing as before: returning an array where each a element is added to the corresponding element of b. map will return [8,19,18,7]. Since there are no more input elements reduce will return that value (the array).

To achieve expected result, use below option using two loops with forEach

const blockList = [[2, 9, 1, 2], [2, 3, 9, 4], [4, 7, 8, 1]];
const result = [];

blockList.forEach((v, index) =>
  v.forEach((val, i) => {
    result[i] = result[i] ? result[i] : 0;
    result[i] += val;
  })
);

console.log(result);

codepen - https://codepen.io/nagasai/pen/yZRrKy?editors=1010

You can use reduce and forEach.

Here we create an array with index we add particular element to particular index. and than just take the values out from object.

const list = [[2, 9, 1, 2],[2, 3, 9, 4],[4, 7, 8, 1]]

let op = list.reduce((op,inp)=>{
   inp.forEach((e,i)=>op[i] = op[i] ? op[i]+e : e)
   return op
},[])

console.log(op)

You can use .reduce in bination with an iterative for...of loop that pulls out the index and value of each inner array using v.entries. Then simply assign them by index to the accumulator Array and add them together.

let expectedResult = list.reduce((a,v) => {
 for(let [i, n] of v.entries()) a[i] = (a[i] || 0) + n
 return a;
}, []);

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

let expectedResult = list.reduce((a,v) => {
 for(let [i, n] of v.entries()) a[i] = (a[i] || 0) + n
 return a;
}, []);

console.log(expectedResult);

Use nested loops:

const blocklist = [[2,9,1,2], [2,3,9,4], [4,7,8,1]], calculatedBlocks = [];
for (let j = 0, sum = 0; j < blocklist[0].length; j++, sum = 0) {
  for (let i = 0; i < blocklist.length; i++) sum += blocklist[i][j];
  calculatedBlocks.push(sum);
}

console.log(calculatedBlocks);

Post a comment

comment list (0)

  1. No comments so far