简体   繁体   English

JavaScript:如何从 Array.reduce() 函数返回映射数组?

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

Why does Code Snippet 1 work while Code Snippet 2 doesn't?为什么代码片段 1有效而代码片段 2无效?

Code Snippet 1:代码片段 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:代码片段 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?如何正确缩短代码片段 1

Why does Code Snippet 1 work while Code Snippet 2 doesn't?为什么代码片段 1 有效而代码片段 2 无效?

Because the callback is executed multiple times, and the new Map you are returning becomes the ar accumulator value in the next call.因为回调执行了多次,而你返回的new Map在下一次调用中就变成了ar累加器值。

How would I shorten Code Snippet 1 correctly?如何正确缩短代码片段 1?

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 .但真正正确的解决方案是根本不使用reducepush ,而只使用mapfilter To remove duplicate ids, keep track of them in a Set , or even better just key another map by them:要删除重复的 id,请在Set跟踪它们,或者甚至更好地通过它们键入另一个映射:

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]
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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