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

241
Vistas
How do I sort array of objects in descending order based on alphanumeric value in Javascript?
var ArrOfObj = [
    { name: "a", value: "BNG2000" },
    { name: "b", value: "BNG2001" },
    { name: "c", value: "CHN-4000" },
    { name: "d", value: "CHN-4004" }
]

I want to sort this array of object by descending order based on the value property.

Expected answer:

var ArrOfObj = [
    { name: "d", value: "CHN-4004" },
    { name: "c", value: "CHN-4000" },
    { name: "b", value: "BNG2001" },
    { name: "a", value: "BNG2000" }
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need a custom comparer function that will use the value property of your objects to make a descending alphabetic sort on your ArrOfObj.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

The comparer, in this demo I shared here, extracts the numeric part from string values and compares them based on how those 2 numbers are relative to each other so that the array will be sorted by value property in a descending manner.

  • BNG2000 (as string) -> 2000 (as number)
  • BNG2001 (as string) -> 2001 (as number)
  • CHN-4000 (as string) -> 4000 (as number)
  • CHN-4004 (as string) -> 4004 (as number)

Sort order: 1: 4004, 2: 4000, 3: 2001, 4: 2000

var ArrOfObj=[
  {name: "a", value:"BNG2000"},
  {name: "b", value:"BNG2001"},
  {name: "c", value:"CHN-4000"},
  {name: "d", value:"CHN-4004"}
]

function customComparer(a, b){
    const value_a = parseInt( getNumberPart(a.value) );
    const value_b = parseInt( getNumberPart(b.value) );    
    if(value_a < value_b) return 1;
    if(value_a > value_b) return -1;
    return 0;
}

//returns the numeric part contained in subject string
function getNumberPart(subject){    
    let value = '';
    const match = subject.match(/(\d+)/m);
    if (match != null)  
      value = match[1];
      
    return value;
}

ArrOfObj.sort( customComparer );
console.log(ArrOfObj);
/*
[
  {
    "name": "d",
    "value": "CHN-4004"
  },
  {
    "name": "c",
    "value": "CHN-4000"
  },
  {
    "name": "b",
    "value": "BNG2001"
  },
  {
    "name": "a",
    "value": "BNG2000"
  }
]
*/

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