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?
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
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.
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.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With