最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Push method not available in reduce' array accumulator? - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 9

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]), []))

发布评论

评论列表(0)

  1. 暂无评论