简体   繁体   中英

JavaScript: How to return mapped array from Array.reduce() function?

Why does Code Snippet 1 work while Code Snippet 2 doesn't?

Code Snippet 1:

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
  }
  return ar;
}, []);
firstEvents = new Map(firstEvents.map(entry => [entry.eventTitle, entry.startDate]));

Code Snippet 2:

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
  }
  return (new Map(ar.map(entry => [entry.eventTitle, entry.startDate])));
}, []);

How would I shorten Code Snippet 1 correctly?

Why does Code Snippet 1 work while Code Snippet 2 doesn't?

Because the callback is executed multiple times, and the new Map you are returning becomes the ar accumulator value in the next call.

How would I shorten Code Snippet 1 correctly?

To make it a single expression, you would use

const firstEvents = new Map(events.reduce(…).map(…));

But really the correct solution would be not to use reduce and push at all, but just map and filter . To remove duplicate ids, keep track of them in a Set , or even better just key another map by them:

const firstEventsById = new Map(events.filter(e =>
  e.isRecurringEvent() && e.isAllDayEvent()
).map(e => {
  var id = e.getId();
  return [id, {
    eventTitle: e.getTitle(),
    // eventId: id,
    startDate: e.getAllDayStartDate(),
    // endDate: e.getAllDayEndDate()
  }];
}).reverse());
const startDatesByTitle = new Map(Array.from(firstEventsById.values(), entry =>
  [entry.eventTitle, entry.startDate]
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM