简体   繁体   中英

Sorting object of lat longs from top left to bottom right

I have an object that looks something like this:

Object {
  "-M2p5oNuWAJFhZKv64ht": Object {
    "latitude": -37.8263853,
    "longitude": 144.9951198
  },
  "-M39Q4SBJbGZjUQHfvGa": Object {
    "latitude": -37.805684,
    "longitude": 144.893994
  },
  "-M39Q4pAz5sF0tF4d3XK": Object {
    "latitude": -37.8086484,
    "longitude": 144.8823838
  },
  "-M39Q4zL7ZNzqdHaJLvZ": Object {
    "latitude": -37.8076142,
    "longitude": 144.8838452
  },
  "-M39Q58FwvBP2HoDZGD9": Object {
    "latitude": -37.808319,
    "longitude": 144.892747
  },
  "-M39Q5Idu-EgkAn0Vd2Q": Object {
    "latitude": -37.8108465,
    "longitude": 144.8798158
  },
  "-M39Q5U8XCq1h4ieo_Db": Object {
    "latitude": -37.802019,
    "longitude": 144.8909805
  }
  ...
}

Imagining that these coordinates relate to the red pins on the below map, I would like to start from the upper most left corner from each pin and sort them as if a square was slowly expanding from that point. I can only think of getting the starting lat long and incrementing +1 to those, then checking if a value is < either variable, repeat. I imagine this is obviously incredibly inefficient and would love a more robust and expandable way.

Thanks

在此处输入图片说明

You want to sort your array by the max value of your 2 coordinates.

myArray.sort((a, b) => {
    const aMax = Math.max(a.latitude, a.longitude);
    const bMax = Math.max(b.latitude, b.longitude);

    if (aMax < bMax) return -1;
    if (bMax < aMax) return 1;
    return 0;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM