DEV Community

Cover image for How to sort array of object using object keys in JavaScript?
Madan Lal
Madan Lal

Posted on

How to sort array of object using object keys in JavaScript?

Here we are going to sort an array of objects using keys that are available in that objects.

For running our javascript code, we use Nodejs. you can check by typing in terminal or cmd that you have Nodejs in your system or not node -v. it will show the version of the node, you have. But if you do not have then you can download it from nodejs.org.

After that create one file named test.js
and we take our dataset

const data = [
  { name: 'madan', age: '12' },
  { name: 'man', age: '13' },
  { name: 'dan', age: '14' },
  { name: 'dam', age: '11' },
  { name: 'ram', age: '17' },
]
Enter fullscreen mode Exit fullscreen mode

Now our data is ready, let's start implementing our logic to sort data. for that, we are going to create a function in which we pass two parameters one is data and another one is key. here data define the above dataset and key define by which key, you want to sort, available in the object like we have just name and age.

function sortDataBy (data, byKey){
   //here your logic code
}
Enter fullscreen mode Exit fullscreen mode

Now inside the function, we create one variable to store our sorted data.

let sortedData;
Enter fullscreen mode Exit fullscreen mode

after that, we are going to check each and every key present in the object with the given key in the variable called byKey.

if(byKey == 'name'){
    //your logic for name
}
else if(byKey == 'age'){
    //your logic for age
}
Enter fullscreen mode Exit fullscreen mode

first we are writing logic for name key

// we use javascript sort function to compare to value
sortedData = data.sort(function(a,b){
   // here a , b is whole object, you can access its property
   //convert both to lowercase
      let x = a.name.toLowerCase();
      let y = b.name.toLowerCase();

   //compare the word which is comes first
      if(x>y){return 1;} 
      if(x<y){return -1;}
      return 0;
    });
Enter fullscreen mode Exit fullscreen mode

now we are writing logic for age key

sortedData = data.sort(function(a,b){
    // here a , b is whole object, you can access its property

    // it will return the difference to sort function and then 
    // sort compare that difference is equal to 0 or smaller than 0 or 
    // greater than 0. on the basis of that it will give sorted number list
      return a.age - b.age;
    })
Enter fullscreen mode Exit fullscreen mode

at the end, just return our data variable sortedData

return sortedData;
Enter fullscreen mode Exit fullscreen mode

after completing our function, we can call it with different keys of the object to check our output.

console.log('sort by age\n');
console.log(sortDataBy(data, 'name'));
console.log('sort by age\n');
console.log(sortDataBy(data, 'age'));
Enter fullscreen mode Exit fullscreen mode

now you can run your file by typing in terminal node test
output will be

sort by age

[
    { name: 'dam', age: '11' },
    { name: 'dan', age: '14' },
    { name: 'madan', age: '12' },
    { name: 'man', age: '13' },
    { name: 'ram', age: '17' }
]
sort by age

[
    { name: 'dam', age: '11' },
    { name: 'madan', age: '12' },
    { name: 'man', age: '13' },
    { name: 'dan', age: '14' },
    { name: 'ram', age: '17' }
]
Enter fullscreen mode Exit fullscreen mode

Last note, for easy to use, I give you the full code here.

const data = [
  { name: 'madan', age: '12' },
  { name: 'man', age: '13' },
  { name: 'dan', age: '14' },
  { name: 'dam', age: '11' },
  { name: 'ram', age: '17' },
];

function sortDataBy (data, byKey){
  let sortedData;
  if(byKey == 'name'){
    sortedData = data.sort(function(a,b){
      let x = a.name.toLowerCase();
      let y = b.name.toLowerCase();
      if(x>y){return 1;}
      if(x<y){return -1;}
      return 0;
    });
  }else{
    sortedData = data.sort(function(a,b){
      return a.age - b.age;
    })
  }
  return sortedData;
}

console.log('sort by age\n');
console.log(sortDataBy(data, 'name'));
console.log('sort by age\n');
console.log(sortDataBy(data, 'age'));

Enter fullscreen mode Exit fullscreen mode

Thank you, Happy coding!!

Top comments (2)

Collapse
 
7tonshark profile image
Elliot Nelson

For the string comparison, you can also simplify using the localeCompare function, which returns a negative, positive, or zero value for you:

return x.localeCompare(y);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kamalx profile image
Kamal Morjal

Thank you! Learned something new today. :)