0

let array = [[1,4], [11], [3,5,7]];

console.log(0+array[0]+array[1]+array[2]);
console.log(array.reduce((acc, value)=>acc+value, 0));

This prints the following on the console :

01,4113,5,7  
01,4113,5,7

I was trying to add all elements of the array and stumbled upon the above code. I know the spread operator and how I can add all the elements. I know what's happening here is concatenation and not addition. I am just not able to understand this output. Can someone tell me what is happening here?

6
  • You can see output, its just concatenating, Read More Commented May 19, 2021 at 13:44
  • [1,4] + [11] will not sum the two objects. It would convert them to strings. Commented May 19, 2021 at 13:46
  • And if an array is converted to a string, comma's are used as a seperator Commented May 19, 2021 at 13:47
  • 1
    No 0 + [1,4] is 01,4. Adding the array [11] will result in 01,411 Commented May 19, 2021 at 13:50
  • 1
    @Wimanicesir - thank you. Got it. It's taking the first element and concatenating. 0 + array[0] gives 01,4 0+array[0]+array[1] gives 01,411 0+array[0]+array[1]+array[2] gives 01,4113,5,7 Commented May 19, 2021 at 13:55

3 Answers 3

0

let array = [[1,4], [11], [3,5,7]];
console.log(array.reduce((acc, value)=>acc+value, 0));

Here, each acc is an array, so (as stated in the comments) the array will be converted to a string (+) and js will implode it with comma's.

To get the sum of all the nested arrays, you'll need calculate the sum of the deeper array before adding:

Example using the new flat();

let array = [[1,4], [11], [3,5,7]];
let sum = array.flat().reduce((acc,value)=> acc + value)
console.log(sum);

Example using a nested reduce:

let array = [[1,4], [11], [3,5,7]];
console.log(array.reduce((acc, value)=> acc + value.reduce((a, b) => a + b, 0), 0));
// 1+4+11+3+5+7
// 31


There are many other options to get the desired results, using the new flat() or an recursive function can be found here;

Sign up to request clarification or add additional context in comments.

Comments

0

Loop through each sub-array on an outer loop and add each number of each sub-array in an inner loop.

let twoDArray = [
  [1, 4],
  [11],
  [3, 5, 7]
];

const sumOfArrays = array => {
  let sum = 0;
  for (let arr of array) {
    for (let num of arr) {
      sum += num;
    }
  }
  return sum;
}

console.log(sumOfArrays(twoDArray));

Comments

-1

To make a long story short, "reduce()" basically performs a loop. Instead of using an actual handwritten loop within your code, the work is done by programming within the JavaScript interpreter itself, in a single efficient operation.

Here is an older StackOverflow post which includes some nice graphics to explain the processes of "map" and "reduce."

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.