19

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.

4 Answers 4

59

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));
5
  • 1
    JS 101: put your ranks outside the callback statement, no need to redefine rank every time...
    – mpowered
    Jul 5, 2017 at 19:35
  • 2
    @mpowered, I think that may be a premature optimization. Browsers should be able to recognize it as a constant and compile it once. You could also write two functions: one that declares rank and returns a second function that does the ranking. Moving rank outside of the function scope pollutes the global scope, and it since it only applies to that function, it's better to have it there.
    – Jason
    Jul 5, 2017 at 21:37
  • @Jason It won't pollute the global scope if you don't put it in the global scope. Code like this will almost never end up in global scope, and relying on VM optimization to fix something you should have done right in the first place is a silly notion. Also, the chances that you're going to use it somewhere else in this case, say, a filter select, is probably pretty high.
    – mpowered
    Jul 7, 2017 at 14:10
  • 1
    Maybe better to move rank outside of the loop, no need to redefine it each time. Oct 2, 2018 at 14:04
  • A good JS compiler (like V8) should be able to see the var is constabt and reused and optimize it accordingly. You could wrap in a second function to avoid polluting the global scope with rank, but that makes the code harder to read.
    – Jason
    Oct 3, 2018 at 12:29
12

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

0
9

7 years later, but is cleaner to just do this.

const order = ["Freshman", "Sophomore", "Junior", "Senior"];
_.sortBy(data, (o) => order.indexOf(o));
2

Do it the super hackish/bad way!!!! Dead simple/insanely confusing :)

function rank(word){
    return Math.abs(113-word.trim().toLowerCase().charCodeAt(1));
}

console.log(rank('freshman')); // 1
console.log(rank('sophomore')); // 2
console.log(rank('junior')); // 4
console.log(rank('senior')); // 12

Edit:

Since people seem to be finding this answer useful, here's an explanation of how it works... It sorts based on one letter in the word provided. Since "sophomore" and "senior" have a duplicate first letter, I chose to sort by the second letter each word has a unique value for that.

This would then order them this way: sEnior, sOphomore, fReshman, jUnior. In order to properly sort them, I subtracted using the character code for Q (113) which is right next to R (for freshman). That means how close the second letter of each word is to Q determines the order. In order to prevent negative numbers, the function takes the absolute value of the result, and returns that.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.