Friday, June 4, 2021

Javascript Practice 71: JS Hero - Nested loops

 
Question: 

Write a function sum that calculates the sum of all elements of a two-dimensional array.

Example: sum([[1, 2], [3]]) should return 6.




Answer: 

function sum (arr) {

let arr2 = arr.flat(); 

return arr2.reduce((a, b) => a + b, 0);

}




> we declare a function sum
> it has 1 parameter 'arr'
> first we create a variable arr2
> we initialize it with the output we get by using the flat() method on 'arr' parameter
> the flat() method flattens an array with an option of 'depth' 
> you can pass in any levels of nesting with the flat () method
> once our array has been flattened, we then return our array with the reduce method
> the reduce method reduces the array elements to a single value
> we use the reduce method to find the sum of all numbers in our array

No comments:

Post a Comment