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

139
Vistas
JS Array Sorting Using Expression

Is there a way to bring the related object to the first index of the array using sort function?

Here is what I tried using sort only

const arr = [{
    id: 'a',
    name: 'test name 1'
  },
  {
    id: 'b',
    name: 'test name 2'
  },
  {
    id: 'c',
    name: 'test name 3'
  }
];

const testId = 'c';


const sortedArr = arr.sort((a, b) => a.id === testId || b.id === testId ? 1 : -1);

console.log(sortedArr); // logs b, a, c but the expected result is c, a, b

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The issue here is because everytime that a OR b are the testId, it will be "bumped". So, if you check only to one value it works.

Here an example :

const arr = [
  {
    id: 'c'
  },
  {
    id: 'a'
  },
  {
    id: 'b'
  }
];

function checkFor(myList, testId) {
    console.log('Checking for ' + testId);
    const sortedArr = arr.sort((a, b) => b.id === testId ? 1 : -1);

    console.log(sortedArr);
}

checkFor(arr, 'c');
checkFor(arr, 'b');

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