Custom sort order by array of objects

I know that we can define our own function to sort an array of json objects. But what if the order is not desc nor asc . For example, let's say my array looks like this:

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

The result should look like this:

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

When all names starting with n are sorted first and then the rest. I 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 to the objects is incorrect. What is wrong here?

+6
source share
1 answer

If you have an arbitrary sort order, one parameter should assign the order to the 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); }); 

If you have many values โ€‹โ€‹in any of the arrays, it might be worth creating a map of values โ€‹โ€‹first and then using sortOrder[a.name] .

+11
source

All Articles