Tuesday, November 27, 2018

JavaScript Array sort by several parameters

Array.prototype allows us to sort array just by 1 parameter. I have created my own method 'sortBy' to fix this gap. The method also allows to sort by desc. Let's say we have the following array
  1. var objects = [{'Name': 'John', 'Age': 23, 'Profession': 'Accountant'},
  2. {'Name': 'Adam', 'Age': 18, 'Profession': 'Engineer'},
  3. {'Name': 'Vik', 'Age': 46, 'Profession': 'Architect'},
  4. {'Name': 'Jane', 'Age': 36, 'Profession': 'Developer'},
  5. {'Name': 'Rikky', 'Age': 28, 'Profession': 'Developer'}];
var objects = [{'Name': 'John', 'Age': 23, 'Profession': 'Accountant'},
    {'Name': 'Adam', 'Age': 18, 'Profession': 'Engineer'},
    {'Name': 'Vik', 'Age': 46, 'Profession': 'Architect'},
    {'Name': 'Jane', 'Age': 36, 'Profession': 'Developer'},
    {'Name': 'Rikky', 'Age': 28, 'Profession': 'Developer'}];
The following function call sorts the array by 'Profession' then by 'Name' descendantly
  1. sortBy(objects, 'Profession', {'Name': 'desc'});
  2. console.table(objects);
sortBy(objects, 'Profession', {'Name': 'desc'});
console.table(objects);
The result will be the following:

Now let's have a look at the method implementation.
  1. var sortBy = function(arr, ...sortByArgs){
  2. arr.sort(function(a,b){
  3. var sortResult = 0;
  4. sortByArgs.forEach(function(arg){
  5. if (sortResult != 0) return;
  6. if(Object.values(arg)[0] == 'desc'){
  7. var propName = Object.keys(arg)[0];
  8. if (a[propName] > b[propName]){
  9. sortResult = -1;
  10. return;
  11. }
  12. if (a[propName] < b[propName]) {
  13. sortResult = 1;
  14. return;
  15. }
  16. }
  17. else {
  18. if (a[arg] < b[arg]){
  19. sortResult = -1;
  20. return;
  21. }
  22. if (a[arg] > b[arg]) {
  23. sortResult = 1;
  24. return;
  25. }
  26. }
  27. });
  28. return sortResult;
  29. });
  30. };
var sortBy = function(arr, ...sortByArgs){
 arr.sort(function(a,b){
   var sortResult = 0;
   sortByArgs.forEach(function(arg){
     if (sortResult != 0) return;
      if(Object.values(arg)[0] == 'desc'){
        var propName = Object.keys(arg)[0];
       if (a[propName] > b[propName]){ 
       sortResult = -1;
       return;
       }
      if (a[propName] < b[propName]) {
       sortResult = 1;
        return;
       }
      }
      else {
     if (a[arg] < b[arg]){ 
       sortResult = -1;
       return;
       }
      if (a[arg] > b[arg]) {
       sortResult = 1;
        return;
       }
       }
    });
    
    return sortResult;
  });
};


You can try it on JSFiddler:
http://jsfiddle.net/AndrewBuntsev/cwt2gbej/
Don't forget to press F12 to display browser's console

No comments:

Post a Comment