'How can I pass more parameters to a custom sort() function?

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?



Solution 1:[1]

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"));

Solution 2:[2]

Yes, have the comparator returned from a generator which takes a param which is the key you want

function compareByProperty(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(compareByProperty('myKey'));

compareByProperty('myKey') returns the function to do the comparing, which is then passed into .sort

Solution 3:[3]

const objArr = [{
    name: 'Z',
    age: 0
  }, {
    name: 'A',
    age: 25
  }, {
    name: 'F',
    age: 5
}]
  
const sortKey = {
    name: 'name',
    age: 'age'
}

const sortArr = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0
    })
}
  
console.log("sortKey.name: ", sortArr(objArr, sortKey.name))
console.log("sortKey.age: ", sortArr(objArr, sortKey.age))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VisioN
Solution 2 Paul S.
Solution 3