I'm trying to .sort() an array of objects, but my javascript knowledge isn't strong enough to rewrite the comparator function to accept an arrow function to find the key on the objects rather than use a string. Any help refactoring this would be appreciated:
My comparison function:
compareValues = (key, order = "ascending") => {
let result = 0;
return function(lhs, rhs) {
if (!(lhs.hasOwnProperty(key) && rhs.hasOwnProperty(key))) {
return result; // property is missing; comparison is impossible
}
const l = lhs[key].toLowerCase() || lhs[key];
const r = rhs[key].toLowerCase() || rhs[key];
result = (l > r) ? 1 : (l < r) ? -1 : 0;
return result * (order === "ascending") ? 1 : -1;
};
};
which is used in the conventional way:
objects.sort(compareValues("name")); // or
objects.sort(compareValues("name", descending));
The goal is to be able to use it thusly:
objects.sort(compareValues(o => o.name));
... but frankly I haven't used JS much until lately, so I suck at it.
comparatorfunction intocompareValues? Based on your function's signature, it expects akey, which looks like it's astring, but you're trying to pass afunctioninstead.keyincompareValues. If it's a function, run it, and use that as the key to look up. If it isn't a function use it as the key.