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];
});