0

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

Ben Shekhtman
  • 385
  • 5
  • 15

0 Answers0