2

I'm totally stuck and blank on how to solve this sort problem.
JS object

o={"items":[  
    {"name":"Name 1","types":[  
        {"type":"Type 4","subtype":"Sub a"}
    ]},  
    {"name":"Name 2","types":[]},  
    {"name":"Name 3","types":[  
        {"type":"Type 1","subtype":"Sub x"}  
    ]}  
]}

I'm trying to sort by type, something along the lines of o.sortByType();

Array.prototype.sortByType = function(){
    this.sort(function(a,b) {
        var ap = a[types][type], bp = b[types][type];
        if(ap!=undefined||bp!=undefined){
            if (ap < bp) {return -1;}
            if (ap > bp) {return 1;}
        }else{
            return 0;
        }
    })
return this;
}

I'm trying to get re-ordered array:
items:
Name 3,
Name 1,
Name 2

Sort function used here works for any non-nested property of item's objects.
If I use a[types][type] in sort, it returns fault, "types" is not defined.
If I use a.types.type, it just returns unmodified array.
Like I said, I am horribly stuck, and any help or pointers would be greatly appreciated.

1
  • What is your sorting condition? Do you want to sort the array by it's "type"? Commented Oct 12, 2011 at 9:14

1 Answer 1

1

I am assuming you want to sort your array by using the type as key. That's the solution:

o.items.sort(function(a,b){
    if(a.types.length == 0 || b.types.length == 0) {
        return b.types.length - a.types.length;
    }
    return a.types[0].type.localeCompare(b.types[0].type);
});

Here is an example.

1
  • This is very cool! Thank you!!! I have never used localeCompare before, but reading up on it as we speak. Again, thank you! Commented Oct 12, 2011 at 11:52

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.