In order to utilize the array.sort() function, a number-returning function must be specified. Typically, it would look something like this:
myArray.sort((item1, item2) => a < b);
However, I am aiming for a different structure:
myArray.sort(by(obj => obj.id))
The desired setup involves:
- Having a function parameter that returns a number from any given input
- Returning another function with 2 arguments (the items to be compared) that also returns a number
- This specific function will then compare the results of the two previous functions
While my intention is clear, I've been facing challenges in implementing this using various methods. Here's one attempt:
by = (getter : any => number): ((any, any) => number) => (x,y) => {
var xValue = getter(x);
var yValue = getter(y);
if (xValue > yValue)
return 1;
else if (xValue < yValue)
return -1;
else return 0;
}
Is this approach on the right path? Any feedback is appreciated!