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

后端 未结 4 1242
醉梦人生
醉梦人生 2020-12-15 10:55

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 att

相关标签:
4条回答
  • 2020-12-15 11:11

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

    0 讨论(0)
  • 2020-12-15 11:15

    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"));
    
    0 讨论(0)
  • 2020-12-15 11:19

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

    0 讨论(0)
  • 2020-12-15 11:36

    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

    0 讨论(0)
提交回复
热议问题