JS数组按日期分组
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS数组按日期分组相关的知识,希望对你有一定的参考价值。
参考技术A 若后台返回格式如下:let data = [
"createdAt": "2020-08-02T11:00:24.580Z", "name": "西瓜",
"createdAt": "2020-08-03T11:00:24.580Z", "name": "水蜜桃",
"createdAt": "2020-08-03T11:00:24.580Z", "name": "樱桃",
"createdAt": "2020-08-02T11:00:24.580Z", "name": "西柚",
]
方法:使用 dayjs(createdAt).format('YYYY-MM-DD') 转换
注:dayjs 安装引用
npm install dayjs --save import dayjs from 'dayjs'
for ( let i=0; i<array.length; i++ )
let createdAt = dayjs(array[i].time);
array[i].createdAt = createdAt;
mapName (array)
let newArray = [];
array.forEach((item, i) =>
let index = -1;
let alreadyExists = newArray.some((newItem, j) =>
if (item.createdAt === newItem.createdAt)
index = j;
return true;
);
if (!alreadyExists)
newArray.push(
createdAt: item.createdAt,
name: [item.name]
);
else
newArray[index].price.push(item.name);
);
return newArray;
以上是关于JS数组按日期分组的主要内容,如果未能解决你的问题,请参考以下文章