Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you apply a custom sort to an array?

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.

like image 415
Kevin Avatar asked May 30 '13 21:05

Kevin


People also ask

How do you sort a custom array?

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.

Can you use sort () on an array?

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.


2 Answers

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));
like image 159
Jason Avatar answered Sep 20 '22 04:09

Jason


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

like image 40
Roman Yudin Avatar answered Sep 22 '22 04:09

Roman Yudin