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 d
Solution 1:
You may add a wrapper:
functioncompareOnKey(key) {
returnfunction(a, b) {
a = parseInt(a[key], 10);
b = parseInt(b[key], 10);
if (a < b) return -1;
if (a > b) return1;
return0;
};
}
arrayOfObjects.sort(compareOnKey("myKey"));
Solution 2:
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).
Solution 3:
Yes, have the comparator returned from a generator which takes a param which is the key you want
functioncompareByProperty(key) {
returnfunction (a, b) {
a = parseInt(a[key], 10);
b = parseInt(b[key], 10);
if (a < b) return -1;
if (a > b) return1;
return0;
};
}
arrayOfObjects.sort(compareByProperty('myKey'));
compareByProperty('myKey')
returns the function to do the comparing, which is then passed into .sort
Solution 4:
const objArr = [{
name: 'Z',
age: 0
}, {
name: 'A',
age: 25
}, {
name: 'F',
age: 5
}]
const sortKey = {
name: 'name',
age: 'age'
}
constsortArr = (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))
Post a Comment for "Js Sort() Custom Function How Can I Pass More Parameters?"