How to sort array on key value in javaScript using Prototype library

We  can sort a JSON  array using this method:

  1. This is the method to sort the array:
    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;
        });
    }
    
    
  2. How to sort the array with data? Just do:
    var arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];
    arr.sortOn("name");
    arr.sortOn("artist");

If we want to convert the array to JSON we have to do this:

  1. var array = [];
    for ( var i=1 ; i< arr.length; i++ ){
            var mComponente = {
    	        name	: 'bob',
    	        artist  : 'rudy',
    	};
            array.push(mComponente);
    }
    
    // convert array into JSON array
    var jsonArray = $.parseJSON(JSON.stringify(array));
    

Reference link: http://stackoverflow.com/questions/16648076/sort-array-on-key-value

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s