Node JS Sort Array of Objects by Value Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

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

let's see very simple lesson 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:'Sagor', 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);

Result:-

[

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

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

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

]

[

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

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

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

]

thank you very much for following up with me.

Tags

Recent Posts

Related Posts