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

标签 javascript arrays sorting nested

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

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/

相关文章:

python - numpy中的加权协方差矩阵

在双指针上调用 qsort 导致段错误

javascript - 在 HTML 文件的脚本 JS 标签中使用 ES6 依赖

javascript - 使用 jQuery 切换显示/隐藏

javascript - 如何使用 jQuery.grep() 过滤多维 JSON 对象

对 Crystal Reports 中的交叉表列进行排序

Linux排序命令: keys with the same start but different length are not sorted in the same order

javascript - ASCII 动画

php - 如何在php mysql中相对于列插入csv数组数据

sorting - 按 etime 对 PS 命令排序