Reputation: 38529
Consider the following array:
var thingsThatMatter = [
{"Colour of hair", "High"},
{"Colour of eyes", "Low"},
{"Colour of shoes", "Medium"}
];
Apologies for the example, but the key part here is the high, medium, low parameter.
That's the data I'm working with (1,2,3 would of been much easier...!)
Is there anyway I can easily sort the array, so that the items run in order - High, Medium, Low?
Or, is there a way I can "get" the item that has the value "Low" as a priority parameter?
Note- the structure of this will be changed to numerical later, however for now, this is what I have to work with.
Upvotes: 0
Views: 432
Reputation: 359966
Use Array.sort()
with a custom compare function.
Here, have a cookie:
var thingsThatMatter = [
["Colour of hair", "High"],
["Colour of eyes", "Low"],
["Colour of shoes", "Medium"]
];
function comparator(a, b) {
a = comparator.priorities[a[1]];
b = comparator.priorities[b[1]];
if (a > b) return 1;
if (a < b) return -1;
return 0;
}
comparator.priorities = {
High: 0,
Medium: 1,
Low: 2
}
thingsThatMatter.sort(comparator);
http://jsfiddle.net/mattball/T3hNm/
Upvotes: 3