Sort array of JSON object by key value easily with JavaScript

·

2 min read

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' }
]