Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array on key value

Tags:

I have a function which sorts by name currently and an array of value / key pairs.

I wonder how can I pass the key on which sort is being performed so I can call the same function every time like so:

var arr = [{name:'bob', artist:'rudy'},
           {name:'johhny', artist:'drusko'},
           {name:'tiff', artist:'needell'},
           {name:'top', artist:'gear'}];

sort(arr, 'name');   //trying to sort by name
sort(arr, 'artist'); //trying to sort by artist

function sort(arr) {
  arr.sort(function(a, b) {
    var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase();
    if (nameA < nameB) //sort string ascending
      return -1;
    if (nameA > nameB)
      return 1;
    return 0; //default return value (no sorting)
   });          
}
like image 890
Toniq Avatar asked May 20 '13 11:05

Toniq


People also ask

How do I sort a string array in PHP?

$strings = array('/root/mandy/c. pdf', '/root/mandy/a. pdf', '/root/mandy/b. pdf'); sort($strings); print_r($strings);


1 Answers

Array.prototype.sortOn = function(key){
    this.sort(function(a, b){
        if(a[key] < b[key]){
            return -1;
        }else if(a[key] > b[key]){
            return 1;
        }
        return 0;
    });
}



var arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];

arr.sortOn("name");
arr.sortOn("artist");
like image 119
Diode Avatar answered Sep 28 '22 09:09

Diode