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:
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]
.