I'd like to sort an array in a customized way.
Example would be a student's classlevel:
_.sortBy(["Junior","Senior","Freshman","Sophomore"], function(classlevel){
// ??
})
Ideally, the sort should return:
["Freshman","Sophomore","Junior","Senior"]
I'm thinking if I could pre-rank the classlevels ahead of time like this:
var classlevelRanked = [{ class: "Junior",
rank: 3
},{ class: "Senior",
rank: 4
},{ class: "Freshman",
rank: 1
},{ class: "Sophomore",
rank: 2
}]
and then apply a sort via:
_.sortBy(classlevelRanked, function(classlevel){
return classlevel.rank;
})
But then I have to strip out the ranks by doing:
.map(function(classlevel){
return classlevel["class"];
})
Is there a more direct way to do this without pre-ranking the classlevels and then stripping it out afterwards?
Thank you.
To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0. The above process will sort the data in descending order.
Just like numeric arrays, you can also sort string array using the sort function. When you pass the string array, the array is sorted in ascending alphabetical order.
You should be able to do something like this:
_.sortBy(["Junior","Senior","Freshman","Sophomore"], function(element){
var rank = {
"Junior" : 3,
"Senior" : 4,
"Freshman" :1,
"Sophomore" :2
};
return rank[element];
});
Fiddle:
http://jsfiddle.net/hKQj8/
Alternatively, if rank
is a constant that may be useful elsewhere, you can define it outside of the _.sortBy
expression and use _.propertyOf
for a more declarative style:
var rank = {
"Junior" : 3,
"Senior" : 4,
"Freshman" :1,
"Sophomore" :2
};
_.sortBy(["Junior","Senior","Freshman","Sophomore"], _.propertyOf(rank));
In addition to Jason's answer:
var list = _.sortBy([{name:"Junior"},{name:"Senior"},{name:"Freshman"},{name:"Sophomore"}], function(element){
var rank = {
"Junior" : 3,
"Senior" : 4,
"Freshman" :1,
"Sophomore" :2
};
return rank[element.name];
});
console.dir(list);
It will help to sort array of objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With