Sorting an array of objects using Javascript

 When working on one of my projects, I had to sort the elements of the JSON array of objects. I did this most of the time from server side but this time I had to do the client side sort.

Here is the solution what I found.

We've two functions one to sort by ascending and other for descending. It expects first parameter as array (of objects) and second parameter the key on basis of which we want to sort.

 
<script>
function sortByKeyDesc(array, key) {
	return array.sort(function (a, b) {
    	var x = a[key]; var y = b[key];
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
	});
}

function sortByKeyAsc(array, key) {
	return array.sort(function (a, b) {
    	var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
	});
}
</script>
Here is the example

<script>
books = [{
  'BookID': 123,
  'BookName': 'Seven Habits of most effective people'
}, {
  'BookID': 234,
  'BookName': 'Why Leaders eat last'
}, {
  'BookID': 345,
  'BookName': 'How to influence people'
}, {
  'BookID': 456,
  'BookName': 'The Tipping point'
}];

sorted_books = sortByKeyAsc(books, 'BookName');
console.log(sorted_books);
</script>
Result will be

[{
  BookID: 345,
  BookName: "How to influence people"
}, {
  BookID: 123,
  BookName: "Seven Habits of most effective people"
}, {
  BookID: 456,
  BookName: "The Tipping point"
}, {
  BookID: 234,
  BookName: "Why Leaders eat last"
}]