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

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

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 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