Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda