【问题标题】:Filter an array in javascript with 2 property用 2 个属性过滤 javascript 中的数组
【发布时间】:2018-09-24 14:57:22
【问题描述】:

这是数组:

如果某人的结果 + GMath 比其他人多,我想将他放在数组的第一位。

我正在制作一个有角度的应用程序。我需要为应用程序过滤它。如果您需要模板或 ts 文件,请在下面评论。

【问题讨论】:

  • 您是要过滤(删除的东西)还是排序(仍然按某种顺序排列的所有内容)或两者兼而有之?
  • place him first in the array. 这不是过滤器,它是一种排序.. 那么您是否只想按“result + GMath”对数组进行排序?
  • 这里没有数组,没有数组就无法排序。
  • @Get_Off_My_Lawn:请立即查看。我已经添加了数组。
  • @Keith 是的,我想通过结果 + GMath 做空

标签: javascript arrays angularjs angular


【解决方案1】:

您需要做的是使用sortb 的总和中减去a 的总和,如下所示:

let arr = [
  {result: 5, GMath: 5},
  {result: 2, GMath: 8},
  {result: 4, GMath: 10},
  {result: 1, GMath: 1}
]

arr.sort((a, b) => (b.result + b.GMath) - (a.result + a.GMath))

console.log(arr)

【讨论】:

  • @Moumitaakter,请注意,您将 IE 用户和使用“旧”版本的更现代浏览器的人排除在外 -> caniuse.com/#feat=arrow-functions
  • 您的代码确实有效。但我不明白 arr.sort((a, b) => (b.result + b.GMath) - (a.result + a.GMath)) 这一行。你能不能更具体一点。以及为什么两个括号之间有 -
【解决方案2】:
// const obj = { admissionStudents: {...} }; // assuming this is the object to begin with
let keys = Object.keys(obj.admissionStudents);
keys.sort((a, b) => {
  return (obj.admissionStudents[b].result + obj.admissionStudents[b].GMath) - (obj.admissionStudents[a].result + obj.admissionStudents[a].GMath);
});

现在keys 将被排序,所以使用这个框住对象。

新列表,

newList = [];
keys.forEach((key) => {
  newList.push(obj.admissionStudents[key]);
});

newList 将是排序列表。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 2017-11-22
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2019-05-29
    • 1970-01-01
    相关资源
    最近更新 更多