I have this code:
let fullConversations = conversationIdsByUser.reduce(async function(acc, conversation) {
const message = await MessageModel.find({ 'conversationId':conversation._id })
.sort('-createdAt')
.limit(1); // it returns an array containing the message object so I just get it by message[0]
return acc.push(message[0]);
},[]);
my accumulator here is an array, message[0] is an object that I want to push. but I have this error:
(node:516) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: acc.push is not a function
Help?
I have this code:
let fullConversations = conversationIdsByUser.reduce(async function(acc, conversation) {
const message = await MessageModel.find({ 'conversationId':conversation._id })
.sort('-createdAt')
.limit(1); // it returns an array containing the message object so I just get it by message[0]
return acc.push(message[0]);
},[]);
my accumulator here is an array, message[0] is an object that I want to push. but I have this error:
(node:516) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: acc.push is not a function
Help?
Share Improve this question asked Aug 17, 2017 at 17:56 gpbaculiogpbaculio 5,96814 gold badges68 silver badges112 bronze badges1 Answer
Reset to default 9This is because Array.prototype.push() returns the new length of the array, not the array itself. Your code will run through one iteration of your reducer, set the accumulative value to an integer, and then fail on the next iteration.
The fix is just return the array after modifying it:
let fullConversations = [{a: 1}, {b: 2}].reduce(function(acc, next) {
console.log(acc.push(next))
return acc
}, []);
console.log(fullConversations)
Note, however, that you should always pass a pure function to Array.prototype.reduce()
. Keeping this rule would have saved you from this problem in the first place. Example:
console.log([{a: 1}, {b: 2}].reduce((mem, next) => mem.concat([next]), []))