[英]js sort() custom function how can i pass more parameters?
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.
谢谢。
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"));
You would need to partially apply the function, eg using bind
: 您需要部分应用该函数,例如使用
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). 或者你只是让
compareOn
返回实际的sort函数,使用外部函数的参数进行参数化(如其他函数所示)。
Yes, have the comparator returned from a generator which takes a param which is the key you want 是的,让比较器从一个生成器返回,该生成器需要一个param,这是你想要的密钥
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
compareByProperty('myKey')
返回执行比较的函数,然后传递给.sort
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.