Function used to sort the array having object literals
npm install json-sortingjavascript
const fs = require("fs");
const { jsonSorting } = require("json-sorting");
// first read and parse the json file
const file = fs.readFileSync("./src/user.json");
const usersArray = JSON.parse(file);
// Now use the sort function
let ascending_order = jsonSorting(usersArray, "name.first", "string", "asc");
let descending_order = jsonSorting(usersArray, "name.first", "string", "desc");
`
Example 1 :
`javascript
//install and import the package
const { jsonSorting } = require("json-sorting");
// example parsed json file
var json = [{
"name": "misty",
"id": 8
}, {
"name": "ash",
"id": 6
}, {
"id": 1
}];
let result = jsonSorting( json, "name", "string");
console.log(result);
// output
[{
"name": "ash",
"id": 6
}, {
"name": "misty",
"id": 8
}, {
"id": 1
}];
`
In the above example it is sorted using the key - name since all the name are string datatype we are giving string as third parameter. If we notice we didnt give forth parameter by default it is arranged in ascending order
> Note if an object doesnt have tht key all the undefined keys objects will be go atlast in the sortingNote if an object doesnt have tht key all the undefined keys objects will be go atlast in the sorting
Example 2 :
`javascript
const { jsonSorting } = require("json-sorting");
var json = [{
"name": {
"first": "anita",
"last": "turner"
},
"email": "anita.turner36@example.com"
},
{
"name": {
"first": "oscar",
"last": "wells"
},
"email": "oscar.wells37@example.com"
},
{
"name": {
"first": "george",
"last": "young"
},
"email": "george.young96@example.com"
}
];
let result = jsonSorting( json, "name.first", "string","desc");
console.log(result);
// output
[{
{
"name": {
"first": "oscar",
"last": "wells"
},
"email": "oscar.wells37@example.com"
},
{
"name": {
"first": "george",
"last": "young"
},
"email": "george.young96@example.com"
},
"name": {
"first": "anita",
"last": "turner"
},
"email": "anita.turner36@example.com"
}
];
``