Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
Sort method with field name passed in

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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(...
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!