Node JS Sort Array of Objects by Value Example

By Hardik Savani May 19, 2021 Category : Node JS

Today, i will let you know example of node js sort array of objects by value. This post will give you simple example of node js sort array of objects by key. This article will give you simple example of node js sort array of objects example. This tutorial will give you simple example of How to sort an array of objects by a property value in node.

let's see very simple example of how to sort array of objects by value in node js. check bellow code:

Example:

Array.prototype.sortBy = function(p) {

return this.slice(0).sort(function(a,b) {

return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;

});

}

objs = [

{ name:'Paresh', age: 32, email: 'paresh@gmail.com'},

{ name:'Hardik', age: 30, email: 'hardik@gmail.com'},

{ name:'Ankit', age: 60, email: 'ankit@gmail.com'},

];

var newObjName = objs.sortBy('name');

console.log(newObjName);

var newObjAge = objs.sortBy('age');

console.log(newObjAge);

Output:

[

{ name: 'Ankit', age: 60, email: 'ankit@gmail.com' },

{ name: 'Hardik', age: 30, email: 'hardik@gmail.com' },

{ name: 'Paresh', age: 32, email: 'paresh@gmail.com' }

]

[

{ name: 'Hardik', age: 30, email: 'hardik@gmail.com' },

{ name: 'Paresh', age: 32, email: 'paresh@gmail.com' },

{ name: 'Ankit', age: 60, email: 'ankit@gmail.com' }

]

i hope it can help you...

Tags :
Shares