比较对象数组中的两个相似值会有些麻烦。
例如,我有以下对象数组:
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,但是不知道如何立即访问数组中的相邻项以进行比较,因为这两种方法似乎都不需要索引参数来进行迭代。如果说得通?
答案 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>
);
});