I have an array of objects I need to sort on a custom function. Since I want to do this several times on several object attributes, I'd like to pass the key name for the attribute dynamically into the custom sort function:
function compareOnOneFixedKey(a, b) {
a = parseInt(a.oneFixedKey)
b = parseInt(b.oneFixedKey)
if (a < b) return -1
if (a > b) return 1
return 0
}
arrayOfObjects.sort(compareByThisKey)
This should become something like:
function compareOnKey(key, a, b) {
a = parseInt(a[key])
b = parseInt(b[key])
if (a < b) return -1
if (a > b) return 1
return 0
}
arrayOfObjects.sort(compareOn('myKey'))
Can this be done in a convenient way?
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.
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
You may add a wrapper:
function compareOnKey(key) {
return function(a, b) {
a = parseInt(a[key], 10);
b = parseInt(b[key], 10);
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
}
arrayOfObjects.sort(compareOnKey("myKey"));
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