如何在相邻项目之间使用map / foreach?

时间:2018-12-31 19:06:39

标签: javascript mongodb dictionary foreach

比较对象数组中的两个相似值会有些麻烦。

例如,我有以下对象数组:

let Activities = [
  {
    "_id": "r6cDEGoW6v6WCWR2M",
    createdAt: ISODate("2018-12-29T21:43:49.723Z"),
    comment: 'my comment 1'
  },
  {
    "_id": "JaMSF88t8o5tMC8GM",
    createdAt: ISODate("2018-12-30T21:43:49.723Z"),
    comment: 'my comment 2'
  }
]

我想检查Activity[0]的createdAt日期是否比Activity[1]短(是)的一天,如果是,那么请console.log(“ Yesterday”);

我一直在尝试使用Map和Foreach,但是不知道如何立即访问数组中的相邻项以进行比较,因为这两种方法似乎都不需要索引参数来进行迭代。如果说得通?

1 个答案:

答案 0 :(得分:0)

forEach可以采用其他参数,包括索引和源数组。我必须对ISODate进行存根并进行原始字符串比较,但这应该给您正确的想法。

const ISODate = date => date;

let activities = [
  {
    "_id": "r6cDEGoW6v6WCWR2M",
    createdAt: ISODate("2018-12-29T21:43:49.723Z"),
    comment: 'my comment 1'
  },
  {
    "_id": "JaMSF88t8o5tMC8GM",
    createdAt: ISODate("2018-12-30T21:43:49.723Z"),
    comment: 'my comment 2'
  }
];

activities.forEach((activity, index, src) => {
  if (index < src.length - 1) {
    const nextActivity = src[index + 1];
    if (activity.createdAt < nextActivity.createdAt) {
      console.log('yesterday');
    }
  }
});

如果这是为了做出反应,那么最好通过array::map函数运行数组。类似于:

activities.map((activity, index, src) => {
  let dateChange;
  if (index < src.length - 1) {
    const nextActivity = src[index + 1];
    dateChange = activity.createdAt < nextActivity.createdAt;
  }
  return (
    <Fragment key={ `${activity.createdAt}-${index}` }>
      <Activity { ...activity }/>
      { dateChange && <Divider />}
    </Fragment>
  );
});