javascript - 自定义排序数组以根据字符串对对象进行排序 - Javascript

标签 javascript arrays sorting

<分区>

我有一个数组,我想根据我的对象上的值对其进行排序。

我的数组看起来像这样:

[
  {
   "name": "Ricard Blidstrand",
   "number": "5",
   "position": "b"
  },
  {
   "name": "Gustaf Thorell",
   "number": "12",
   "position": "fw"
  },
  {
   "name": "Rasmus Bengtsson",
   "number": "13",
   "position": "mv"
  }
]

我想按照position-key的顺序排序:

mv > b > fw

我需要这样写吗,还是我写错了?

if(a === "b" && b === "b") {
 return 0;
} else if (a === "b" && b === "mv") {
 return 1;
} 

最佳答案

需要先指定优先级数组。

var priority = [ "mv", "b", "fw"];

现在根据这个对你的数组进行排序

arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );

演示

var arr = [{
    "name": "Ricard Blidstrand",
    "number": "5",
    "position": "b"
  },
  {
    "name": "Gustaf Thorell",
    "number": "12",
    "position": "fw"
  },
  {
    "name": "Rasmus Bengtsson",
    "number": "13",
    "position": "mv"
  }
];

var priority = [ "mv", "b", "fw"];

arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );

console.log(arr);     

关于javascript - 自定义排序数组以根据字符串对对象进行排序 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48517575/

相关文章:

javascript - 在 bootstrap typeahead 上使用 html 输入数据字段属性

javascript - JavaScript 对象属性可以引用同一对象的另一个属性吗?

c - 如何在 C 中将 int8_t 数组转换为 int32_t 数组

java - 如何按长度对字符串进行排序

javascript - HTML - 覆盖状态栏链接位置显示

javascript - HTML 和 CSS : How to lay out a div tag with width:100% and left:300px

php - Mysql 查询似乎可以工作,但仍然出现错误?

javascript - 空数组在比较时返回 false 但当它单独返回 true 时......为什么这样

ruby-on-rails - ruby rails : Find records without Sorting

c - 尝试运行一个排序 C 程序,该程序通过命令行(Mac 终端)接收输入