我有一个相当经典的同时对多个字段进行排序的案例。对我来说困难的是传递带有字段的数据以从单独的数组中进行排序。
const arrayToSort = [
{
Country: "Cyprus",
Date: new Date(2001, 0, 1),
CreateBy: "William",
},
{
Country: "Belarus",
Date: new Date(1999, 0, 1),
CreateBy: "Yuliana",
},
{
Country: "Denmark",
Date: new Date(2019, 0, 1),
CreateBy: "Ava",
},
{
Country: "Albania",
Date: new Date(2000, 0, 1),
CreateBy: "Zachary",
}
];
const sortFields = ["Country", "CreateBy", "Date"];
const descending = [true, false, true];
const sortedArray = arrayToSort.sort((a, b) => {
return arrayToSort.forEach((field, index) => {
const isDate = !isNaN(Date.parse(a[field]));
if (isDate) {
const dateA = new Date(a[field]).getTime();
const dateB = new Date(b[field]).getTime();
if (descending[index] && dateA < dateB) {
return -1;
}
if (dateA > dateB) {
return 1;
}
return 0;
}
if (descending[index] && a[field] < b[field]) {
return -1;
}
if (a[field] > b[field]) {
return 1;
}
return 0;
})
})
console.log(sortedArray);
如果我有静态数量的元素,我会知道该怎么做。如果我不知道数组中的字段数怎么办?我应该在这里使用 forEach 吗?当我 console.log sortedArray
时,没有任何变化。
答案 0 :(得分:1)
我将从一个函数开始,该函数按字段和降序布尔对 2 个对象进行排序
<?= implode(PHP_EOL, $arr) ?>
然后您可以在 const sortBy = (a,b,field,desc) => {
if(a[field]<b[field]) return desc ? 1 : -1
else if(a[field]>b[field]) return desc ? -1 : 1
else return 0;
};
(和 sortFields
)数组的循环中使用它:
descending