JavaScript-根据属性按特殊顺序对对象数组进行排序 [英] JavaScript - sort array of objects, by a property based on a special order

查看:80
本文介绍了JavaScript-根据属性按特殊顺序对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个属性的对象数组.给定以下数组:

I have an array of objects with multiple properties. Given the following array:

var people = [
      {name: "allen", age: 33, color:"green"},
      {name: "jon", age: 23, color:"blonde"},
      {name: "silver", age: 54, color:"yellow"},
      {name: "james", age: 52, color:"grey"},
      {name: "flint", age: 25, color:"pink"},
      {name: "beilly", age: 31, color:"blonde"},
      {name: "bwones", age: 47, color:"grey"},
      {name: "sas", age: 35, color:"green"},
      {name: "jackson", age: 234, color:"yellow"},
      {name: "leonsardo", age: 12, color:"brown"},
      {name: "dicaeprio", age: 73, color:"pink"},
      {name: "sylvfester", age: 35, color:"blonde"},
      {name: "alleen2", age: 33, color:"green"},
      {name: "jofn2", age: 23, color:"blonde"},
      {name: "sdilver2", age: 54, color:"yellow"},
      {name: "jamaes2", age: 52, color:"grey"}
    ];

我需要按color属性对该数组进行排序,但是要以特殊的方式,首先按green,然后按yellow,然后按brown,再按pink,再按grey,最后通过blonde.我在此处

I need to sort this array by color property, but in a special manner, first by green, then by yellow, then by brown then by pink, then grey and lastly by blonde. I read here and here, but having hard time to generate a compactor based upon my needs. Since this is just a demo array and my real data will be a much larger arrays, the sorting mechanism should be quicker than n^2.

推荐答案

这是您的比较器

var sortOrder = {green: 0, yellow: 1, brown: 2, pink: 3, grey: 4, blonde: 5};

people.sort(function (p1, p2) {
   return sortOrder[p1.color] - sortOrder[p2.color];
});

这篇关于JavaScript-根据属性按特殊顺序对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆