gpt4 book ai didi

javascript - JS中如何对嵌套数组按数字排序?

转载 作者:行者123 更新时间:2023-12-01 02:43:05 25 4
gpt4 key购买 nike

我想按工资对嵌套数组进行排序领取最高薪水的人以及以得到最低的人结束一。我不想考虑货币...我不知道该怎么做...提前致谢

Array
(
[0]=>Array
(
[firstName]=>John
[lastName]=>Doe
[age]=>35
[salary]=>Array
(
[gbp]=>"180"
[eur]=>“”
[usd]=>""
)
)
[1]=>Array
(
[firstName]=>Maria
[lastName]=>Anders
[age]=>26
[salary]=>Array
(
[gbp]=>""
[eur]=>"100"
[usd]=>""
)
)
[2]=>Array
(
[firstName]=>Thomas
[lastName]=>Hardy
[age]=>31
[salary]=>Array
(
[gbp]=>""
[eur]=>""
[usd]=>"224"
)
)
)

最佳答案

看起来您发布了 php。

无论如何,看看sort功能:

var numbers = [{
age: 10,
salary: {
gbp: 10,
eur: 0,
usd: 0
}
}, {
age: 2,
salary: {
gbp: 0,
eur: 345,
usd: 0
}
}, {
age: 100,
salary: {
gbp: 0,
eur: 0,
usd: 23
}
}, {
age: 50,
salary: {
gbp: 0,
eur: 432,
usd: 0
}
}];

numbers.sort(function(a, b) {
// Get the sum of salaries in the a object
let aAmt = Object.values(a.salary).reduce((s, v) => s + v, 0)
// Get the sum of salaries in the b object
let bAmt = Object.values(b.salary).reduce((s, v) => s + v, 0)
// Calculate the difference
return bAmt - aAmt
})

console.log(numbers);

关于javascript - JS中如何对嵌套数组按数字排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47428155/

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