Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!