How to I use reduce() to console.log on each iteration?

JavaScript

I have the solution below working properly but would like to do it with the reduce method. How would I go about doing that?

function main(arr) {
    let max = arr[0];
    arr.forEach((value, index) => {
        if (value >= max) {
            max = arr[index]
            console.log(max);
        }
    })
}

main([1,  3,  8,  4,  10,  12,  3,  2,  24]);

Expected Result (each number on a separate line) : 1 3 8 10 12 24

Answer

With the reduce method

[1,  3,  8,  4,  10,  12,  3,  2,  24].reduce((acc, cur) => {
  if (acc < cur) {
    console.log(cur)
    acc = cur
  }
  return acc
}, 0)

Leave a Reply

Your email address will not be published. Required fields are marked *