要按照给定的条件对多个数组对象进行排序,可以使用JavaScript的Array.sort()方法和自定义比较函数来实现。以下是一个示例解决方案:
// 示例数组对象
const data = [
{ name: 'A', distance: 10, rating: 4, liked: true },
{ name: 'B', distance: 5, rating: 3, liked: false },
{ name: 'C', distance: 8, rating: 5, liked: true },
{ name: 'D', distance: 12, rating: 2, liked: true }
];
// 自定义比较函数
function compare(a, b) {
// 按照 liked 属性进行排序,liked 为 true 的排在前面
if (a.liked && !b.liked) {
return -1;
}
if (!a.liked && b.liked) {
return 1;
}
// 如果 liked 属性相同,则按照 distance 属性进行排序,距离越小越靠前
if (a.distance < b.distance) {
return -1;
}
if (a.distance > b.distance) {
return 1;
}
// 如果 distance 属性相同,则按照 rating 属性进行排序,评级越高越靠前
if (a.rating > b.rating) {
return -1;
}
if (a.rating < b.rating) {
return 1;
}
// 如果 rating 属性相同,则按照 name 属性进行排序,按字母顺序排列
return a.name.localeCompare(b.name);
}
// 调用 Array.sort() 方法进行排序
data.sort(compare);
// 输出排序结果
console.log(data);
这段代码首先定义了一个示例数组对象data
,其中包含了多个数组对象。然后定义了一个自定义比较函数compare
,该函数根据给定的排序条件进行比较。在比较函数中,首先按照liked
属性进行排序,liked
为true
的排在前面。然后如果liked
属性相同,则按照distance
属性进行排序,距离越小越靠前。如果distance
属性相同,则按照rating
属性进行排序,评级越高越靠前。最后如果rating
属性相同,则按照name
属性进行排序,按字母顺序排列。
最后,调用Array.sort()
方法,并传入自定义比较函数compare
进行排序。排序后的结果将会存储在原始数组data
中。你可以通过console.log()
输出排序结果。