Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How Reduce function really work in JavaScript?

I’m trying to use reduce function in order to find the max length array in arrays
so I tried this approach at first but it didn’t work

const arrays = [[1],[3,3,4],[3,4],[4,5],[6]]
let maxLength = arrays.reduce( (acc, cur) => {
    return acc.length > cur.length ? acc.length : cur.length
})

console.log(maxLength) // output : 1

so I tried to get the length in another way and it worked

const arrays = [[1],[3,3,4],[3,4],[4,5],[6]]
let maxLength = arrays.reduce( (acc, cur) => {
    return acc.length > cur.length ? acc : cur
}).length

console.log(maxLength) // output : 3

Can someone Explain what is the difference between the two approaches ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the first code, the reduce function is returning a number, while in the second, it is returning an array. When you’re returning a number, the next time your function is called, it takes the length of a number, not an array. The second code is correct, because you’re taking the length of an array every time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading