I'm pretty new to JavaScript, but I am trying to have a generic sort method I can pass to my sorts. At the moment, I have a poor implementation, because the objects I sort may have different fields I want to sort on:
export function sortByName( a, b ) {
if ( a.name < b.name ){
return -1;
}
if ( a.name > b.name){
return 1;
}
return 0;
}
export function sortByDescription( a, b ) {
if ( a.description < b.description ){
return -1;
}
if ( a.description > b.description){
return 1;
}
return 0;
}
I'd like to create a method that takes extra parameters. FieldName, and Desc (Bool). So that I can specify the field in the object, and the direction.
Something like:
export function sortByField( a, b, fieldName, isDesc ) {
if ( a.[fieldName] < b.[fieldName] ){
return -1;
}
if ( a.[fieldName] > b.[fieldName]){
return 1;
}
return 0;
}
And then some logic to handle the isDesc. But then the sort call fails as it doesn't pass those fields.
this.state.templates.sort(sortByDescription).map(template => (
I'm not sure how to add the extra parameters. Sort seems to accept a method with 2 parameters only. Is there a way to achieve a single generic method, that allows sorting on a specific field on the objects being sorted?
Maybe I cannot use .sort, and need to create my own version of sort?
As Kunal mentioned, just use a[fieldName] and b[fieldName]. Do not pass the function directly as a parameter to sort but instead do something like this
array.sort((a, b) => {
//possibly some logic here
sortByDescription(a, b, "myField", true);
}).map(...