function totalVolume(...boxes) {
return boxes.reduce((a,b)=> a + b.reduce((c,d)=> c * d,1),0);
}
console.log(totalVolume([4, 2, 4], [3, 3, 3], [1, 1, 2], [2, 1, 1]))
the question was
Given an array of boxes, create a function that returns the total volume of all those boxes combined together. A box is represented by an array with three elements: length, width and height.
For instance, totalVolume([2, 3, 2], [6, 6, 7], [1, 2, 1]) should return 266 since (2 x 3 x 2) + (6 x 6 x 7) + (1 x 2 x 1) = 12 + 252 + 2 = 266.
Please try to be specific
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
Seems to me you may be over-thinking a little. Reduce works well here, yes - but you only really need one or maybe two reduce functions.
Suppose we had a similar situation, but let’s say area rather then volume. We are given a two value array for each square, [3,14], and we need an inner function to calculate that. Just do the function for one thing first:
const area = ([length, width]) => {
return length*width
}
Only really needed one reduce for the outermost array. If the ([length, width]) part confused, there is a great fcc lesson on array deconstruction (I’m on my phone, or I’d find it for you).
I get it now,I am not very comfortable with reduce yet.So when i saw the double reduce function in a single line i got really confused,Btw thank you for the explanation.
We could have done that without the deconstruction, simply using the array indices inside our function, but i find the “let’s turn our array into individual values” to be easier to write, and understand… With practice.