I am looking at this question:
The
sort
method for arrays can take an argument that is a comparison function with two parameters—say, x and y. The function returns a negative integer if x should come before y, zero if x and y are indistinguishable, and a positive integer if x should come after y. Write calls, using arrow functions, that sort:
- An array of positive integers by decreasing order
- An array of people by increasing age
- An array of strings by increasing length
Here is my code:
const posIntByDcrOrd = [5,4,3,2,1]
const peopleIncAge = [10,15,20,25,30]
const strIncLength = ['a','ab','abc','abcd']
const compFunc = (x,y) => {
let sumNeg = y - x
let sumPos = y + x
if(indexOf(x) < indexOf(y)) { console.log(sumNeg) }
else if( indexOf(x) > indexOf(y)) { console.log(sumPos) }
else { return 0 }
}
posIntByDcrOrd.sort(compFunc(5,4))
The idea behind this code is this: if you can sum the indexes of x and y elements of the arrays, you can get a negative integer, since x will be lower than y and y will be higher than x, which satisfies the conditions. But when I try to run this, I got a reference error of course. How can I access the index positions of x and y in the sorted array? I am open to other solutions as well.
P.S.: These arrays are made-up for easing the thinking process.