Node JS Sort Array of Objects by Value Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Create and Use .env File in Node JS?
- Axios HTTP requests in Node JS Example
- Node JS Http Request with Headers Example
- Node JS Make HTTP Delete Request Example
- How to run node js server on https using self-signed certificate?
- Node JS Express Form Submission Example
- Node JS Multer Rename Uploaded File Example
- Node JS Resize Image Before Upload using Multer Sharp
- Multiple File Upload in Node JS using Multer Example
- Node js Express Image Upload using Multer Example
- Laravel Authenticate User in NodeJS with Socket io using JWT