Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom sort order on array of objects

I know we can define our custom sort function of array of json objects. But what if the order is neither desc nor asc. For example lets say my array looks like:

[ {
    name: 'u'
  },
  {
    name: 'n'
  },
  {
    name: 'a'
  },
  { 
    name: 'n',
  } 
]

Output should look like:

[ {
    name: 'n'
  },
  {
    name: 'n'
  },
  {
    name: 'a'
  },
  { 
    name: 'u',
  } 
]

Where all the names starting with n are sorted first and then the rest. I have tried the following custom sort function:

_sortByName(a, b){
        if (a.name === 'n'){
            return 1;
        } else if(b.name === 'n'){
            return 1;
        } else if(a.name < b.name){
            return 1;
        } else if(a.name > b.name){
            return -1;
        }
    }

But the order returned for objects is wrong. What is going wrong here?

like image 259
faizanjehangir Avatar asked Jul 05 '16 19:07

faizanjehangir


People also ask

How do I sort an array of objects in es6?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort a custom array?

To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0. The above process will sort the data in descending order.

Can we sort array of objects?

We can sort an array of objects in JavaScript by using our built-in Arrays. sort() method, however, we must pass a custom function to our built-in sort method. The function is needed for the comparison of the properties based on which we want to sort our array of objects.


1 Answers

If you have an arbitrary sort order, one option is to assign the order to an array and then use indexOf:

var sortOrder = ['n', 'a', 'u'];
var myArray = [{
    name: 'u'
  },
  {
    name: 'n'
  },
  {
    name: 'a'
  },
  {
    name: 'n'
  }
];
myArray.sort(function(a, b) {
  return sortOrder.indexOf(a.name) - sortOrder.indexOf(b.name);
});

console.log(myArray);

If you have many values in either array, it might be worthwhile creating a value-index map first and then using sortOrder[a.name].

like image 93
nrabinowitz Avatar answered Oct 24 '22 10:10

nrabinowitz