简体   繁体   English

按数组对对象数组进行排序

[英]Sorting an array of objects by an array

I have an array of objects like so; 我有很多这样的对象;

var orders = [
  {
    status: "pending"
  },
  {
    status: "received"
  },
  {
    status: "sent"
  },
  {
    status: "pending"
  }
]

I want to sort this array of objects based on the value of the status key, but so that the order of the objects matches the order of the array of the possible values of the status key; 我想根据status键的值对对象数组进行排序,但是对象的顺序要与status键的可能值数组的顺序相匹配。

var statuses = ["pending", "sent", "received"]

Therefore, after sorting, the two "pending" objects would be first, followed by the "sent" object, and finally the "received" object. 因此,排序后,将首先是两个"pending"对象,然后是"sent"对象,最后是"received"对象。

How can I do this? 我怎样才能做到这一点?

You can do this with sort() and indexOf() . 您可以使用sort()indexOf()

 var orders = [{ status: "pending" }, { status: "received" }, { status: "sent" }, { status: "pending" }] var statuses = ["pending", "sent", "received"] var result = orders.sort(function(a, b) { return statuses.indexOf(a.status) - statuses.indexOf(b.status) }) console.log(result) 

You can use the sort() function: 您可以使用sort()函数:

 var statuses = ["pending", "sent", "received"]; var orders = [ { status: "pending" }, { status: "received" }, { status: "sent" }, { status: "pending" } ]; orders.sort(function(a, b) { return statuses.indexOf(a.status) - statuses.indexOf(b.status); }); console.log(orders); 

Use Array#sort method to sort the array of objects. 使用Array#sort方法对对象数组进行排序。 Where use an object to store the index of keys which helps to avoid using Array#indexOf method(which is slower). 使用对象存储键索引的位置,这有助于避免使用Array#indexOf方法(速度较慢)。

 var orders = [{ status: "pending" }, { status: "received" }, { status: "sent" }, { status: "pending" }]; var statuses = ["pending", "sent", "received"]; // generate the object which holds the index in array // or use an object instead of array which holds the index var index = statuses.reduce(function(obj, k, i) { obj[k] = i; return obj; }, {}) console.log( orders.sort(function(a, b) { return index[a.status] - index[b.status]; }) ) 

You could use an object as hash table for the sort order. 您可以将对象用作哈希表以进行排序。

 var orders = [{ status: "pending" }, { status: "received" }, { status: "sent" }, { status: "pending" }], statuses = { pending: 1, sent: 2, received: 3 }; orders.sort(function (a, b) { return statuses[a.status] - statuses[b.status]; }); console.log(orders); 

Can use methods like indexOf() within sort callback but more efficient is to build hashmap of the indices first 可以在排序回调中使用诸如indexOf()之类的方法,但更有效的方法是首先构建索引的哈希图

var statIndex = statuses.reduce(function(a,c,i){
   a[c] = i;
   return a
},{})

orders.sort(function(a,b){
   return statIndex[a.status] - statIndex[b.status]
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM