Array.reduce() in JavaScript is a bit quirky, and I had avoided it until now, but I put it together just to understand it.
Array.reduce() is, in a nutshell, a function that collects the elements of an array and returns a single output.
First, the basics
const arr = ["A", "B", "C"]; const ret = arr.reduce( (prev, current)=>{ return prev + ' - ' + current; }); console.log(ret); // A - B - C
This is OK.
Then, if the initial value is used
const arr = ["A", "B", "C"]; const ret = arr.reduce( (prev, current)=>{ return prev + ' - ' + current; }, "START"); console.log(ret); // START - A - B - C
This is also OK.
The problem is that if one element
const arr = ["A"]; const ret = arr.reduce( (prev, current)=>{ return prev + ' - ' + current; }); console.log(ret); // A
A function is not called unless it is preceded by an element.
However, if an initial value is set, the function is called because the initial value is before the first element.
const arr = ["A"]; const ret = arr.reduce( (prev, current)=>{ return prev + ' - ' + current; }, "START"); console.log(ret); // START - A
Another thing to watch out for is zero elements. This will result in a run-time error.
const arr = []; const ret = arr.reduce( (prev, current)=>{ return prev + ' - ' + current; }); console.log(ret); // run-time error
If there are zero elements but initial values, as you can imagine, it is okay. And, as in the case of 1 element and no initial value, the function is not called.
const arr = []; const ret = arr.reduce( (prev, current)=>{ return prev + ' - ' + current; }, "START"); console.log(ret); // START
Usage examples
Based on the above, the output of an object in an array, with one line of text per object and a newline at the end of each line, should look something like the following.
const arr = [ {name:"A", id:1}, {name:"B", id:2}, {name:"C", id:3}, ]; const ret = arr.reduce( (prev, current)=>{ return prev + JSON.stringify(current) + "¥n"; }, ""); console.log(ret); // {"name":"A", "id":1} // {"name":"B", "id":2} // {"name":"C", "id":3} //
If you know the behavior of Array.reduce(), it's like that, but I'm not sure if it's intuitive and easy to understand...
Cause.Array.reduce() cannot put processing into the first elementThe reason for this is that the process is forced to use an empty initial value to force the process to be inserted into the
I feel that the original usage is to use Array.map() for preprocessing, rather than Array.reduce() alone, as shown below.
const arr = [ {name:"A", id:1}, {name:"B", id:2}, {name:"C", id:3}, ]; const ret = arr.map( (v)=>{ return JSON.stringify(v) + "\n"; }).reduce( (prev, current)=>{ return prev + current; }); console.log(ret); // {"name":"A", "id":1} // {"name":"B", "id":2} // {"name":"C", "id":3} //