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

100
Visualizações
Sort array of objects by reference array

I have two array of objects, they are essentially copies but the reference array uses a different order.

let result = {"articleData":[{"id":"1","identifier":"Article1"},{"id":"2","identifier":"Article2"},{"id":"3","identifier":"Article3"},{"id":"4","identifier":"Article4"},{"id":"5","identifier":"Article5"},{"id":"6","identifier":"Article6"}]};

let resultReference = {"articleData":[{"id":"3","identifier":"Article3"},{"id":"4","identifier":"Article4"},{"id":"1","identifier":"Article1"},{"id":"2","identifier":"Article2"},{"id":"6","identifier":"Article6"},{"id":"5","identifier":"Article5"}]};

What I want to do is: currently I get some data from my API but it is in the wrong order (how it currently is in "result" array). I want the data to be in the exact same order as the "resultReference" array but how can I achieve this? Is there a minimal approach?

https://jsfiddle.net/g1rmhq9f/

Thanks for any advice

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Presented below is one possible way to achieve the desired objective.

Code Snippet

// custom sort method
const mySort = (arr, refArr) => (
  // use structured-clone to deep-clone "arr"
  // to avoid mutating/modifying it
  structuredClone(arr).
  sort(
    (
      { id: aid }, { id: bid  }     // de-structure & rename "id" props
    ) => (                          // a's ref-index minus b's ref-index 
      refArr.findIndex(({ id }) => id === aid) -
      refArr.findIndex(({ id }) => id === bid)
    )
  )
);

let result = {"articleData":[{"id":"1","identifier":"Article1"},{"id":"2","identifier":"Article2"},{"id":"3","identifier":"Article3"},{"id":"4","identifier":"Article4"},{"id":"5","identifier":"Article5"},{"id":"6","identifier":"Article6"}]};

let resultReference = {"articleData":[{"id":"3","identifier":"Article3"},{"id":"4","identifier":"Article4"},{"id":"1","identifier":"Article1"},{"id":"2","identifier":"Article2"},{"id":"6","identifier":"Article6"},{"id":"5","identifier":"Article5"}]};

console.log(
  "sorted version of result object's articleData array: ",
  mySort(result?.articleData, resultReference?.articleData)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Inline comments added to the snippet above.

about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming "I want the data to be in the exact same order as the "resultReference" array" means you just want the ID to be in ascending order, here is a much simpler solution:

let resultReference = {"articleData":[{"id":"3","identifier":"Article3"},{"id":"4","identifier":"Article4"},{"id":"1","identifier":"Article1"},{"id":"2","identifier":"Article2"},{"id":"6","identifier":"Article6"},{"id":"5","identifier":"Article5"}]};

resultReference.articleData.sort(function(a, b) {
  let id1 = parseInt(a.id);
  let id2 = parseInt(b.id);

  return id1 - id2;
})

/*
Output:
{
  articleData: [
    { id: '1', identifier: 'Article1' },
    { id: '2', identifier: 'Article2' },
    { id: '3', identifier: 'Article3' },
    { id: '4', identifier: 'Article4' },
    { id: '5', identifier: 'Article5' },
    { id: '6', identifier: 'Article6' }
  ]
}
*/

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