1

I have a map that is made of an array of arrays. I need to sort this map based on the second value per array (index 1). Since this map is essentially an array, I'm wondering why values.sort() yields an error stating that it is an undefined function. How can I sort such without changing the values map (and also preferably not introducing another variable)?

var values = new Map([
  [3, 123],
  [1, 562],  
  [4, 345]
])
console.log(values.get(1)) // returns 562 - okay

values.sort((x,y) => {
    return x[1] - y[1]
})
kzaiwo
  • 1,558
  • 1
  • 16
  • 45
  • If you care about order, then a `Map` is not likely the best data structure. – crashmstr Oct 18 '21 at 14:34
  • Sort the array that you pass into the Map constructor as instructed in the linked answer – Ruan Mendes Oct 18 '21 at 14:34
  • @crashmstr Why not? [Entries are guaranteed to be returned in insertion order](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries). There may be a need for a quick hash lookup and for ordered iteration. – Ruan Mendes Oct 18 '21 at 14:35
  • @JuanMendes If the map has additional contents added later, then the sort order would still be insertion order and not in "sorted" order. They neither state that the Map never subsequently changes nor that they add more data later, but that would be a consideration. – crashmstr Oct 18 '21 at 14:48

0 Answers0