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

132
Visualizações
sorting array with multiple sort parameters with state object in React

I have a locationServices array which holds an array of locations, and a nested services array in state.

My functionality below consists of creating a new array, calculating and adding some additional properties to a locationService instance, pushing to the respective array and then sorting the respective array.

  let locationsWithDistance = []
  let locationsWithNeedMatch = []
  let locationsWithDistanceAndNeedMatch = []


  locationServices?.map((location) => {
    location['distance'] = calcLocationDistance(location)
    location['matchesNeed'] = calcNeedMatches(location)
    locationsWithDistance.push(location)
    locationsWithNeedMatch.push(location)
    locationsWithDistanceAndNeedMatch.push(location)

    locationsWithDistance.sort(function (a, b) {
      return a.distance - b.distance;
    });

    locationsWithNeedMatch.sort(function (a, b) {
      return b.matchesNeed - a.matchesNeed;
    });

    locationsWithDistanceAndNeedMatch.sort(function(a, b){
      // need to sort by both distance and matches
    })
  })

the first array sorts by distance, the second sorts by a need match. For my third array I would like to sort by both distance and need match. How can I achieve this?

DISERED OUTPUT

[
  {
    location_id: 1,
    name: 'location 1',
    matchesNeed: true,
    distance: 4.7
  },
  {
    location_id: 3,
    name: 'location 3',
    matchesNeed: true,
    distance: 9.9
  },
  {
    location_id: 4,
    name: 'location 4',
    matchesNeed: false,
    distance: 5.4
  },
  {
    location_id: 5,
    name: 'location 5',
    matchesNeed: false,
    distance: 5.8
  },
  {
    location_id: 6,
    name: 'location 6',
    matchesNeed: false,
    distance: 8.7
  },
]

the array returns first the needMatches if they are true, and whichever is closest to the user, and then after the rest of the needs are returned by closest distance with the userNeed of false

about 4 years ago · Juan Pablo Isaza
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