Skip to content

All topics  /  Node.js

How to Sort JSON Array in Node JS?

Node.js ·

Hi Friends,

Here, I will show you how to sort JSON array in node js. let’s discuss sort JSON array in node.js. it's a simple example of sorting a JSON array according to one property in node js. I’m going to show you how do I sort a JSON array in node js.

There are many ways to use how to sort JSON array in node js. I will give you examples using sortJsonArray(). This function is used to create a sort JSON array in node js. Node js provide sort-json-array npm package used to sort JSON array.

let's see below a simple example with output:

Install Node JS


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app
cd my-app

 
npm init

Install with npm:

$ npm install sort-json-array --save

Example:

index.js

//npm install sort-json-array
sortJsonArray = require('sort-json-array');
//sort an array of JSON objects by a property:
user = [
    { name: 'c', location: "Developer" },
    { name: 'a', location: "Piyush"},
    { name: 'b', location: "Kamani" },
];
console.log(sortJsonArray(user, 'name'));

Output:

[
    { name: 'a', location: 'Piyush' },
    { name: 'b', location: 'Kamani' },
    { name: 'c', location: 'Developer' }
]