DEV Community

abhsiksah
abhsiksah

Posted on

Power of JS: reduce

// You will be given an array of several arrays that each contain integers and your goal is to write a function that will sum up all the numbers
// in all the arrays. For example, if the input is [[3, 2], [1], [4, 12]] then your program should output 22 because 3 + 2 + 1 + 4 + 12 = 22.
// Solve without and with reduce.

//without reduce

const sumofsubarray = (arr) =>{

let result = 0;
arr.map((elem)=>{

// console.log(elem)
elem.map((eleme)=>{

    result+=eleme;
})


})

return result
Enter fullscreen mode Exit fullscreen mode

}

// console.log(sumofsubarray([[3, 2], [1], [4, 12]]))

//with reduce function

const arr = [[3, 2], [1], [4, 12]]

console.log(arr.reduce((t,e)=>t.concat(e)).reduce((t,e)=>t+e))

Top comments (0)