push does not return the array; rather it returns undefined. Therefore, for the first iteration, accumulator will be the empty array, but for the second iteration it will be undefined.

I’d recommend concat instead:

const ids = ['123', '456'];

// want to get [{id:123}, {id:456}]
const rs = ids.reduce((accumlator, currentVal) => accumlator.concat([{id: currentVal}]), []);

…or use map for a simpler implementation:

const rs = ids.map(id => ({ id }));

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top