Search code examples
javascriptes6-map

How do I iterate through an ES6 Map in order?


The default iteration order through an ES6 map is insertion order. How do you iterate through it in numeric/lexicographic order?


Solution

  • Unfortunately there's no ordered map in Javascript like there is in better languages (e.g. C++'s std::map, or Rust's BTreeMap). There are third party ones like btree-typescript (the benchmarks section lists some other implementations).

    So you could use a map that is stored sorted. If you are using the ES6 Map you either have to insert the values in order and never change them, or you have to collect all of the keys into an array and then sort them. If you're doing it once it's actually quicker than using a BTreeMap (in Rust anyway, I assume the same is true in Javascript). But normally it is probably better to use a B-tree map.

    function sortedNumberKeys<V>(map: Map<number, V>): number[] {
      return [...map.keys()].sort((a, b) => a - b);
    }
    
    function sortedStringKeys<V>(map: Map<string, V>): string[] {
      return [...map.keys()].sort();
    }
    
    const m: Map<string, number> = new Map();
    
    for (const key of sortedStringKeys(m)) {
      const val = m.get(key);
    }