js sort() custom function how can i pass more parameters?

ぃ、小莉子 提交于 2019-11-27 15:01:44

问题


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 dinamically 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)

should became 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? thanks.


回答1:


You would need to partially apply the function, e.g. using bind:

arrayOfObjects.sort(compareOn.bind(null, 'myKey'));

Or you just make compareOn return the actual sort function, parametrized with the arguments of the outer function (as demonstrated by the others).




回答2:


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



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/14491695/js-sort-custom-function-how-can-i-pass-more-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!