3 回答
TA贡献1865条经验 获得超7个赞
我的方法:
data = [ {date: 4/15/2020, 9:46:07 PM, value: "abc"},
{date: 4/15/2020, 11:19:18 PM, value: "xyz"},
{date: 4/16/2020, 1:25:13 PM, value: "def"},
{date: 4/17/2020, 5:6:17 PM, value: "pqr"}
];
// Create a map for the dates
let dataMap = {};
data.forEach((el) => {
let tempDate = getDateFormat(el.date);
if (tempDate in dateMap) {
dateMap[tempDate].value.push(el.value);
} else {
dateMap[tempDate] = {
date: tempDate,
value: [el.value],
};
}
});
data = [];
// Fill the data
Object.keys(dataMap).forEach((el) => data.push(dataMap[el]));
// The format of date
function getDateFormat(date) {
return (
date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear()
);
}
TA贡献1828条经验 获得超3个赞
使用非常方便reduce
const data = [
{date: "4/15/2020, 9:46:07 PM", value: "abc"},
{date: "4/15/2020, 11:19:18 PM", value: "xyz"},
{date: "4/16/2020, 1:25:13 PM", value: "def"},
{date: "4/17/2020, 5:6:17 PM", value: "pqr"}
]
const newArray = data.reduce((acc, dt) => {
const date = new Date(dt.date)
const y = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date)
const m = new Intl.DateTimeFormat('en', { month: 'numeric' }).format(date)
const d = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date)
const formatedDate = `${m}/${d}/${y}`
const dateAcc = acc[formatedDate]
if (!dateAcc) {
acc[formatedDate] = {
date: formatedDate,
value: [dt.value]
}
} else {
acc[formatedDate].value.push(dt.value)
}
return acc
}, {})
console.log(newArray)
TA贡献1828条经验 获得超3个赞
const res = []
for (let i = 0; i < data.length; i++) {
if (res.every(r => r.date !== data[i].date)) {
res.push(data[i])
} else {
const index = res.findIndex(r => r.date == data[i].date)
res[index] = {...res[index], value: [res[index].value, data[i].value]}
}
}
console.log(res)
它的工作原理是 id 在 data.value 中有一个值
添加回答
举报