Merge an array that contains multiple arrays, in order to execute .reduce()

I’m trying to sum the elements of an array:

const toBeSummed = 8,0,8,6,0,8,0,6,4,9,5,5,9,1,2,6

This array is actually made up of some other arrays that I have .push() the contents into the ‘toBeSummed’ array. These elements are:

let lastNumber = 8
let evens = [ 0, 8, 6, 0, 8, 0, 6, 4 ]
const minusNineNumbers = [ 9, 5, 5, 9, 1 ]
let underNine = [ 2, 6 ]

When I run the code to .reduce() the ‘toBeSummed’ array I’m not getting the result I want. I think because these are separate arrays.

const finalSum = toBeSummed.reduce((accumulator, currentValue) => {
console.log('The value of accumulator: ', accumulator);
console.log('The value of currentValue: ', currentValue);
return accumulator + currentValue;
}); console.log('Final sum: ’ + finalSum);
}

/*PRINTS
The value of accumulator: 8
The value of currentValue: [ 0, 8, 6, 0, 8, 0, 6, 4 ]
The value of accumulator: 80,8,6,0,8,0,6,4
The value of currentValue: [ 9, 5, 5, 9, 1 ]
The value of accumulator: 80,8,6,0,8,0,6,49,5,5,9,1
The value of currentValue: [ 2, 6 ]
Final sum: 80,8,6,0,8,0,6,49,5,5,9,12,6

I have tried to .join() the ‘toBeSummed’ array together so I don’t get this separated result, but it doesn’t seem to be working:

console.log('This is the joined array ’ + toBeSummed.join());

Can someone tell me how to join these together so I can use .reduce to sum the ‘toBeSummed’ array?

thanks

You need to use the Array.Prototype.Flat method to return an array with embedded arrays into one. The Array.Prototype.Join method returns a string.

1 Like