Vuk
Vuk

Reputation: 35

Sorting nested arrays in JavaScript

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.

Upvotes: 2

Views: 425

Answers (1)

styrr
styrr

Reputation: 829

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.

Upvotes: 1

Related Questions