gpt4 book ai didi

javascript - 如何使用 parseFloat 使用对象属性按降序排序?

转载 作者:行者123 更新时间:2023-12-03 08:16:55 24 4
gpt4 key购买 nike

我有以下test code

var arr = [{
EmployeeInfo: [{
annualWage: "24000"
}],
name: "Tim",
surname: "Jones",
id: "1111"
}, {
EmployeeInfo: [{
annualWage: "52000"
}],
name: "Terry",
surname: "Phillips",
id: "2222"
}];

console.log(arr);

arr.sort(function (a, b) {

return parseFloat(a.EmployeeInfo[0].annualWage) - parseFloat(b.EmployeeInfo[0].annualWage);
});

console.log(arr);

我想按年薪对数组进行排序,将收入最高的人放在开头。似乎无法让它工作......我错过了什么明显的事情?

最佳答案

您只需颠倒顺序即可。 <强> The rules 如下:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

所以基本上:

arr.sort(function(a, b) {
return parseFloat(b.EmployeeInfo[0].annualWage) - parseFloat(a.EmployeeInfo[0].annualWage);
});

关于javascript - 如何使用 parseFloat 使用对象属性按降序排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33893000/

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