ItSolutionStuff.com

Node JS Sort Array of Objects by Value Example

By Hardik Savani • May 19, 2021
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: Node JS
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Create and Use .env File in Node JS?

Read Now →

Axios HTTP requests in Node JS Example

Read Now →

Node JS Http Request with Headers Example

Read Now →

Node JS Make HTTP Delete Request Example

Read Now →

How to run node js server on https using self-signed certificate?

Read Now →

Node JS Express Form Submission Example

Read Now →

Node JS Multer Rename Uploaded File Example

Read Now →

Node JS Resize Image Before Upload using Multer Sharp

Read Now →

Multiple File Upload in Node JS using Multer Example

Read Now →

Node js Express Image Upload using Multer Example

Read Now →

Laravel Authenticate User in NodeJS with Socket io using JWT

Read Now →