I don't know why I get this result when I use reduce consecutively in javascript

Issue

I found something strange while testing this and that.

function func1(data) {
    return data.reduce((prev, x) => {
        prev.push(x);
        return prev}, []);
}

let arr = [1, 2, 3, 4, 5]

func1(arr).reduce((x) => {
    console.log(x)
    return x;
})

output:

1
1
1
1

My expectation is that it returns an array, so I wanted to print the values ​​for [1, 2, 3, 4, 5] in the next reduce, but it failed. Why did you get this result?

Solution

Reduce operation reduces inputs with the operation supplied in your function starting with an initial value (or the first element if no initial value supplied) Each iteration takes the previous response and next array element to evaluate the same function.

Since your function does not have an initial element it takes your first element "1" to initialize. And your function does not evaluate anything but returns the element you first supplied. Therefore you always print your first element as the result.

You can check these examples to better understand reduce operation.

Answered By – Aras

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published