【问题标题】:JavaScript sort array descending by nested object [duplicate]JavaScript按嵌套对象降序排序数组[重复]
【发布时间】:2019-10-27 06:30:47
【问题描述】:
我正在尝试对这个数组进行排序,但它对我不起作用。我一定是在做一些愚蠢的事情,有人可以看看并告诉我有什么问题吗?
var fruits = [{
config: {
priority: 99
}
}, {
config: {
priority: 1
}
}, {
config: {
priority: 10
}
}];
document.getElementById("demo").innerHTML = JSON.stringify(fruits);
function myFunction() {
let l = fruits.sort(sort);
document.getElementById("demo").innerHTML = JSON.stringify(l);
}
function sort(item1, item2) {
return item1.config.priority < item2.config.priority;
}
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
【问题讨论】:
标签:
javascript
arrays
sorting
【解决方案1】:
应该从sort() 回调返回一个整数。从第二个值中减去第一个值
var fruits = [{
config: {
priority: 99
}
}, {
config: {
priority: 1
}
}, {
config: {
priority: 10
}
}];
document.getElementById("demo").innerHTML = JSON.stringify(fruits);
function myFunction() {
let l = fruits.sort(sort);
document.getElementById("demo").innerHTML = JSON.stringify(l);
}
function sort(item1, item2) {
return item2.config.priority - item1.config.priority;
}
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
【解决方案2】:
使用 - 不使用
const fruits = [{ config: { priority: 99 } }, { config: { priority: 1 } }, { config: { priority: 10 } }];
document.getElementById("demo").innerHTML = JSON.stringify(fruits);
function myFunction() {
let l = fruits.sort(sort);
document.getElementById("demo").innerHTML = JSON.stringify(l);
}
function sort({ config: { priority: p1 }}, { config: { priority: p2} }) {
return parseInt(p1) - parseInt(p2);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>