How to get an index of an array element within a sort comparison function?

Tags: , , , ,



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:

  1. An array of positive integers by decreasing order
  2. An array of people by increasing age
  3. 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.

Answer

There is an abundance of Q&A on this site that deal with sorting. Your attempt seems to show you haven’t seen how numbers are commonly sorted in JavaScript. For instance this Q&A, and many others, provide the right way to do it.

Some comments on your attempt:

  • There is no indexOf available to you within the callback of sort. You don’t need that information. Just subtract the second value from the first to get an ascending (non-decreasing) result. Perform the subtraction in the other sense to get a descending (non-increasing) result. The internals of the sort function will use that return value to perform a sort algorithm. No indexes need to be known to you in that process.

  • The assignment about people is probably not correctly reflected in your sample array, as now it just looks the same as the first input (an array of numbers). It is quite probable that an array of objects was intended. For example:

    const peopleIncAge = [{name: "Helen", age: 20},
                          {name: "John", age: 15},
                          {name: "Anne", age: 30},
                          {name: "Clark", age: 25},
                          {name: "Joy", age: 10}]
    
  • Your input arrays are already sorted as they would need to be output. For testing any solution, it is better to have them shuffled.

Each of the three exercises needs a different callback function for the sort function:

const positives = [1, 3, 5, 4, 2];
const people = [{name: "Helen", age: 20},
                {name: "John", age: 15},
                {name: "Anne", age: 30},
                {name: "Clark", age: 25},
                {name: "Joy", age: 10}];
const strings = ['abc', 'a', 'abcd', 'ab'];

console.log(positives.sort((x, y) =>  y - x));  // decreasing
console.log(people.sort((x, y) =>  x.age - y.age)); // increasing age
console.log(strings.sort((x, y) =>  x.length - y.length)); // increasing length


Source: stackoverflow