in this video i have explained how you can Sort array of JSON object by key value easily with JavaScript
for those of you who don't want to watch video here is the code:
suppose this is the array of JSON object
var data = [
{ id: 2, name: "FIAT", active: true, parentId: "1" },
{ id: 11, name: "BMW", active: true, parentId: "1" },
{ id: 3, name: "RENAULT", active: false, parentId: "1" },
{ id: 0, name: "AUDI", active: true, parentId: "1" },
];
now if you want to sort this array of json object by id
basis you can simply do this by
data = data.sort((a, b) => {
if (a.id < b.id) {
return -1;
}
});
result would be :
[
{ id: 0, name: 'AUDI', active: true, parentId: '1' },
{ id: 2, name: 'FIAT', active: true, parentId: '1' },
{ id: 3, name: 'RENAULT', active: false, parentId: '1' },
{ id: 11, name: 'BMW', active: true, parentId: '1' }
]
you can read more about JavaScript array.sort method from here
if you want to sort this array of JSON object by name
basis (i.e, sort it alphabetically) you can simply do this by
data = data.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
});
result would be :
[
{ id: 0, name: 'AUDI', active: true, parentId: '1' },
{ id: 11, name: 'BMW', active: true, parentId: '1' },
{ id: 2, name: 'FIAT', active: true, parentId: '1' },
{ id: 3, name: 'RENAULT', active: false, parentId: '1' }
]
if you want to sort this array of JSON object by active
basis (i.e, sort it on boolean value) you can simply do this by
data = data.sort((a, b) => {
if (a.active == true && b.active == false) {
return -1;
}
if (b.active == true && a.active == false) {
return -1;
}
});
result would be :
[
{ id: 3, name: 'RENAULT', active: false, parentId: '1' },
{ id: 2, name: 'FIAT', active: true, parentId: '1' },
{ id: 11, name: 'BMW', active: true, parentId: '1' },
{ id: 0, name: 'AUDI', active: true, parentId: '1' }
]
Top comments (7)
after taking the feedback of my last post i provided the code as well
let me know if i can do something else too to improve the article
Nice! if you want to improve your posts maybe you can set the language to this code blocks using markdown like that:
So they got colourised accordingly, example:
"easier" way to do is :
data.sort((prev,next)=>prev.id-next.id)
which will return
[
{
"id": 0,
"name": "AUDI",
"active": true,
"parentId": "1"
},
{
"id": 2,
"name": "FIAT",
"active": true,
"parentId": "1"
},
{
"id": 3,
"name": "RENAULT",
"active": false,
"parentId": "1"
},
{
"id": 11,
"name": "BMW",
"active": true,
"parentId": "1"
}
]
for more informations w3schools.com/js/js_array_sort.asp
You should always consider local conditions when sorting.
Adding the localeCompare reference
Another way to reach that is using Intl.Collator which has better performance for large arrays.
Thanks, good concise explanation.