Mads Mads - 1 month ago 12
Node.js Question

Sort map based on object property while keeping key

I have created a map that contains a list of products, and the shop closest by that is selling that product, like so:

var products = new Map()
products.set('product_key', {
shop: 'shop_key',
distance: 1.2
})


Now what I would like to do is sort the entire map on the distance property, so that I can list the products by proximity to my location.

I use a map because I also need to go in and be able to find the distance to one specific product using the key.

Answer

One way is to have an array of keys sorted by distance:

"use strict";

var products = new Map()
products.set('product_key', {
    shop: 'shop_key',
    distance: 1.2
})
products.set('product2_key', {
    shop: 'shop2_key',
    distance: 0.1
})
console.log(products);

var keysByDistance = Array.from(products.keys()).sort((a, b) => products.get(a).distance - products.get(b).distance);
console.log(keysByDistance.map(key => products.get(key)));

Outputs:

Map {
  'product_key' => { shop: 'shop_key', distance: 1.2 },
  'product2_key' => { shop: 'shop2_key', distance: 0.1 } }
[ { shop: 'shop2_key', distance: 0.1 },
  { shop: 'shop_key', distance: 1.2 } ]