Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript - Sort key value pair object based on value?


Let’s say the following is our object −

var details = [
   { studentId: 100, name: "John" },
   { studentId: 110, name: "Adam" },
   { studentId: 120, name: "Carol" },
   { studentId: 130, name: "Bob" },
   { studentId: 140, name: "David" }
];

To sort the above key-vale pair object, use sort().

Example

Following is the code −

var details = [
   { studentId: 100, name: "John" },
   { studentId: 110, name: "Adam" },
   { studentId: 120, name: "Carol" },
   { studentId: 130, name: "Bob" },
   { studentId: 140, name: "David" }
];
details = details.sort(function (obj1, obj2) {
   return obj1.name.localeCompare(obj2.name);
});
console.log(details);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo253.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo253.js
[
   { studentId: 110, name: 'Adam' },
   { studentId: 130, name: 'Bob' },
   { studentId: 120, name: 'Carol' },
   { studentId: 140, name: 'David' },
   { studentId: 100, name: 'John' }
]