gpt4 book ai didi

javascript - 如何在由逗号分隔值的键分隔的数组中排序

转载 作者:行者123 更新时间:2023-12-01 16:04:26 25 4
gpt4 key购买 nike

如何在以逗号分隔值作为日期的键分隔的单个数组中进行排序。

旧版 Timeseries 正在以以下格式发送数据

arr1 = ['3/13/20,2179','3/14/20,2727', '3/14/20,1024' , '3/14/20,3020', '3/13/20,100', '3/13/20,190']

我正在努力按照以下格式对其进行排序关键是按所有必需值分组的日期

arr1 = [3/13/20,2179,100,190,3/14/20,2727,1024,3020]

任何指针/提示都会有所帮助。

最佳答案

迭代日期,split key得到datecount。拆分date-string,如果你想按日期排序。并在排序回调函数中返回比较的差异。

先按日期排序再统计

arr1 = [
"3/13/20,2179",
"3/14/20,2727",
"3/14/20,1024",
"3/14/20,3020",
"3/13/20,100",
"3/13/20,190",
];
const sort = (data) => {
return data.sort((x, y) => {
const [mm, dd, yy, num] = x.split(/[/,]/);
const [mm1, dd1, yy1, num1] = y.split(/[/,]/);
const d1 = new Date(dd, mm, yy).getTime();
const d2 = new Date(dd1, mm1, yy1).getTime();
if (d1 !== d1) return d1 - d2;
return Number(num) - Number(num1);
});
};
console.log(sort(arr1));

更新:分组日期

arr1 = [
"3/13/20,2179",
"3/14/20,2727",
"3/14/20,1024",
"3/14/20,3020",
"3/13/20,100",
"3/13/20,190",
];
const group = (data) => {
const mapped = data.reduce((map, item) => {
const [date, num] = item.split(",");
if (!map[date]) map[date] = [];
!map[date].push(num);
return map;
}, {});
let result = [];
for (const key in mapped) {
const element = mapped[key];
result = result.concat(key).concat(element);
}
return result;
};
console.log(group(arr1));

关于javascript - 如何在由逗号分隔值的键分隔的数组中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61168123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com