Sort Object in Javascript

Posted on Feb - 2017

by krishna singh

Sorting Objects in Javascript can be done using function with two parameters:

Ex:

var employees = [];
employees.push({name:"bhc",age:24})
employees.push({name:"abc",age:42})
employees.push({name:"djs",age:12})
employees.push({name:"clm",age:34})
employees.push({name:"eny",age:34})

var sortByAge = function(ob1,ob2){
	return ob1.age - ob2.age
}
var sortByName = function(ob1,ob2){
	return ob1.name.localeCompare(ob2.name)
}
console.log(employees.sort(sortByName))

Tips: If you want to reverse the order of sorting just replace code with ob2.age - ob1.age or ob2.name.localeCompare(ob1.name)