Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda