0

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.

3
  • Do you mean high, medium, and low will be numbers and you need to sort the structure based on that? Commented Apr 29, 2012 at 14:36
  • 2
    That's not syntactically valid JS, btw. Did you mean for the elements to be arrays, or objects? Commented Apr 29, 2012 at 14:36
  • 1
    Have a look at these: stackoverflow.com/… Commented Apr 29, 2012 at 14:38

1 Answer 1

3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I'll place a side-bet that the OP meant for the array to contain objects not arrays. (That is, his typo was , for :, not { for [. We'll see...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.