我有一个用例,我将获得多个变量每天的平均数据。日期和值以未排序的方式在 2 个数组中返回。我需要按升序对日期以及值数组中的排序值进行排序。根据日期,现在得到的值是正确的。但我无法正确对两个数组进行排序。即,如果我尝试对日期数组进行排序,则无法获得特定日期的值。有什么办法可以解决这个问题吗?
代码片段是,
let avgValue = [ { _id: { year: 2019, month: 12, day: 11 }, value: 19.83 },
{ _id: { year: 2019, month: 12, day: 10 }, value: 17.88 },
{ _id: { year: 2019, month: 12, day: 9 }, value: 32.58 },
{ _id: { year: 2019, month: 12, day: 6 }, value: 1 },
{ _id: { year: 2019, month: 12, day: 5 }, value: 33.82 } ];
[ { _id: { year: 2019, month: 12, day: 11 }, value: 26 },
{ _id: { year: 2019, month: 12, day: 10 }, value: 40.38 },
{ _id: { year: 2019, month: 12, day: 9 }, value: 35.2 },
{ _id: { year: 2019, month: 12, day: 6 }, value: 2 },
{ _id: { year: 2019, month: 12, day: 5 }, value: 38.91 } ];
**avgValue is a mongodb query which returns the above array for every variable**
let dates = [ '11/12/2019','10/12/2019','9/12/2019','8/12/2019',
'7/12/2019','6/12/2019','5/12/2019','4/12/2019'];
let dbValues=[],dbDates=[],concatenatedDate,newdates=[],constArray=[];
let avgDates = avgValue.map((date,i)=>(date._id.year&&date._id.month&&date._id.day)?
constArray.push(date._id.day+"/"+date._id.month+"/"+date._id.year):null);
avgValue.forEach(async data=>{
concatenatedDate = data._id.day+"/"+data._id.month+"/"+data._id.year;
dates.map((newDate,j)=>{
if(!constArray.includes(newDate) && !newdates.includes(newDate) && i==j){
dbValues.push(0);
newdates.push(newDate);
}else if(newDate===concatenatedDate ){
dbValues.push(data.value);
}
});
dbDates.push(newdates);
}
预期输出是,
值:[0,77,1,0,0,200,15,22],
标签:[2019年4月12日,2019年5月12日, 2019 年 6 月 12 日, 2019 年 7 月 12 日, 2019 年 8 月 12 日, 2019 年 9 月 12 日, 2019 年 10 月 12 日, 2019年11月12日]
最佳答案
这不是最快的方法,但如果您不想实现排序算法,您可以合并、排序和取消合并数组。
const values = [22,0,0,15,200,1,77]
const labels = ["11/12/2019","9/12/2019","7/12/2019","10/12/2019","9/12/2019","6/12/2019","5/12/2019"];
// merge
const merged = [];
for (let i = 0; i < values.length; ++i) {
merged.push([values[i], labels[i]]);
}
// sort
merged.sort((a,b) => new Date(a[1]).getTime() - new Date(b[1]).getTime());
// unmerge
const resValues = [];
const resLabels = [];
for (const mergedValue of merged) {
resValues.push(mergedValue[0]);
resLabels.push(mergedValue[1]);
}
// log
// resValues: [ 77, 1, 0, 0, 200, 15, 22 ]
// resLabels: [ '5/12/2019',
// '6/12/2019',
// '7/12/2019',
// '9/12/2019',
// '9/12/2019',
// '10/12/2019',
// '11/12/2019',
// ]
关于javascript - 如何在node js中同时对日期和各个日期的值数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59284640/