jQuery: sorting JSON objects in AJAX

I was working on a web app which featured an extended search using several select boxes and input fields. The results returned by the PHP script were in JSON format. I wanted to order such results by taking one of the object's properties as a reference. This task implied array sorting.

The JSON output is similar to the following:


[{
	"a": 1,
	"b": true
},
{
	"a": 5,
	"b": false
},
{
	"a": 3,
	"b": true
}]

This is a plain JSON array containing several objects. Each object has an a property with a different integer number. As you can see, numbers are returned in a random order so our goal is to use these numbers to rearrange the array in a progressive fashion (1, 3, 5 and so on).

Our sorting action must take place just after the JSON array is returned by the AJAX call:


$(function() {
	$('#get').on('click', function() {
		$.ajax({
			url: 'json.php',
			dataType: 'json',
			data: null,
			type: 'GET',
			success: function(json) {
				
				// Sorting: typeof json === Array
				
				var sorted = json.sort(function (a, b) {
    				if (a.a > b.a) {
      					return 1;
      				}
    				if (a.a < b.a) {
     					 return -1;
     				}

    				return 0;
			   });
			   
			   var str = '';
				
				$.each(sorted, function(index, value) {
					str += ' ' + value.a;	
				});
				
				$('#output').text(str); // 1, 3, 5
			},
			
			error: function(xhr, status, text) {
				console.log(status + ' ' + text);
			}
		});
	});
});

To sum up:

  • The returned JSON output is an array whose members are JSON objects.
  • Each object should have at least one property in common.
  • Properties should share the same data type.

Practically speaking, your server-side script should be designed to return an array of objects instead of a list of objects.

Back to top