tags:

views:

59

answers:

2

Hi,

I have a multidimensional array, the primary array is an array of [publicationID][publication_name][ownderID][owner_name]. What I am trying to do is sort the array by owner name and then by publication_name. I know in JavaScript you have Array.sort(), into which you can put a custom function, in my case i have:

function mysortfunction(a, b) {
var x = a[3].toLowerCase();
var y = b[3].toLowerCase();

return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

This is fine for just sorting on the one column, namely owner_name, but how do I modify it to sort on owner_name, then publication_name?

Thanks, R.

+3  A: 

If owner names differ, sort by them. Otherwise, use publication name for tiebreaker.

function mysortfunction(a, b) {

  var o1 = a[3].toLowerCase();
  var o2 = b[3].toLowerCase();

  var p1 = a[1].toLowerCase();
  var p2 = b[1].toLowerCase();

  if (o1 != o2) {
    if (o1 < o2) return -1;
    if (o1 > o2) return 1;
    return 0;
  }
  if (p1 < p2) return -1;
  if (p1 > p2) return 1;
  return 0;
}
dcp
Thank you, I think I read a few posts online and just got confused, looking for something much more complicated, but this was perfect. Thanks, R.
flavour404
looks like you are returning true or false instead of a greater or less than zero-
kennebec
It was more or less pseudocode based on OP's code just to give him/her the right idea, but I corrected it. Thanks for pointing it out. By the way, it seems that using return o1 > o2 works (I had the inequality operator backwards). But I did the -1, 0, 1 thing just to be safe :).
dcp
A: 

This is handy for alpha sorts of all sizes. Pass it the indexes you want to sort by, in order, as arguments.

Array.prototype.alphaSort= function(){
    var itm, L=arguments.length, order=arguments;

    var alphaSort= function(a, b){
        a= a.toLowerCase();
        b= b.toLowerCase();
        if(a== b) return 0;
        return a> b? 1:-1;
    }
    if(!L) return this.sort(alphaSort);

    this.sort(function(a, b){
        var tem= 0,  indx=0;
        while(tem==0 && indx<L){
            itm=order[indx];
            tem= alphaSort(a[itm], b[itm]); 
            indx+=1;        
        }
        return tem;
    });
    return this;
}

var arr= [[ "Nilesh","Karmshil"], ["Pranjal","Deka"], ["Susants","Ghosh"], ["Shiv","Shankar"], ["Javid","Ghosh"], ["Shaher","Banu"], ["Javid","Rashid"]];

arr.deepSortAlpha(1,0);

kennebec