Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push method not available in reduce' array accumulator?

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?

like image 791
gpbaculio Avatar asked Jan 03 '23 14:01

gpbaculio


1 Answers

This 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]), []))
like image 71
bowheart Avatar answered Jan 06 '23 11:01

bowheart