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

208
Vistas
How to order by ascending and descending JSON with a condition in lodash or javascript

I want to sort by ascending and descending order of the array of object below using javascript or lodash. The conditions are below:

  1. This array will have objects with duplicate id
  2. I want to sort the array based on 'name' and get the unique 'number' fields in an array based on the 'name' sort with a specific 'id'.

This is the data.

var data = [
  { id: 1, age: 36, name: 'ram', number: 11},
  { id: 2,  age: 40, name: 'sam', number: 11 },
  { id: 3, age: 37, name: 'roy', number: 11 },
  { id: 1, age: 41, name: 'fil', number: 12 },
  { id: 2,  age: 43, name: 'joy', number: 12 },
  { id: 3, age: 46, name: 'john', number: 12 }
]

Expected output when sorting based on name when id='1' and in ascending order:

[12,11]

Expected output when sorting based on name when id='2' and in descending order:

[11,12]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to split up your problem:

  1. filter the array on id === x;
  2. sort the resulting array;
  3. map the resulting values so you only extract the number:

var data = [
  { id: 1, age: 36, name: 'ram', number: 11},
  { id: 2,  age: 40, name: 'sam', number: 11 },
  { id: 3, age: 37, name: 'roy', number: 11 },
  { id: 1, age: 41, name: 'fil', number: 12 },
  { id: 2,  age: 43, name: 'joy', number: 12 },
  { id: 3, age: 46, name: 'john', number: 12 }
]

const id = 1;
const result = data
  .filter(row => row.id === id)
  .sort((a, b) => a.name.localeCompare(b.name))
  .map(row => row.number);
  
console.log(result);

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