1

Is there a way to performance-efficiently insert a key-value pair in a specific place of a Map object?

The problem I'm trying to solve is storing two paired values (one is an absolute floating point 'index', that can range anywhere from 0.00 to 9675.75, another is a floating point value associated with that 'index') in a certain order. In essence, I want to 'reassociate' each absolute 'index' to an abstract [0, 1, 2, 3, ...] index, without losing said absolute 'index'. As of right now I've tried the following:

  • Regular Array. I've tried to convert floating point 'index' to integers so that they can be used as indices of an array, but that effectively would create a so-called 'holey array', which works very inefficiently and slowly for my use case. Another thing I tried with arrays is to create a 2d array, where each element stores a sub-array, that in turn has 'index' as its first, and value as its second element. However, this solution is also suboptimal, since I need to find an index that has an absolute index inside of it through .findIndex(i => i[0] === abs_index_i_search_for), which is also too sluggish.
  • Typed Array. It would be a perfect match for my problem, but, alas, it lacks much needed .splice().
  • Object. Again, a perfectly valid data type, but doesn't have a concept of order, and thus methods that deal with it.

After a bit of googling, I found a Map object which fits my purposes. It can store keys (absolute 'indices' in my case), values, and most importantly, keep them in order of insertion! However, for some reason I can't find any information on working directly with the order of a Map, which is weird since I'm perfectly capable of finding the first key-value pair, implying that the order is not only correct, but also accessible. Am I missing something?

Jørgen Tau
  • 89
  • 2
  • 9
  • No. A map is not meant to be an ordered collection either. Use an array for that purpose. – Bergi Jun 01 '20 at 16:15
  • In your array, you should use binary search instead of `findIndex`. – Bergi Jun 01 '20 at 16:15
  • @Bergi In other words, there is no practically feasible way to use Maps as sequences? Because I can't seem to find a way to use arrays effectively, since my sequence of absolute 'indices', although sorted in a ascending numeric order, may contain holes (i.e. indices with 0 value, which I automatically remove). – Jørgen Tau Jun 01 '20 at 16:42
  • 1
    Exactly. A `Map` is a key-value lookup structure, not a sequence that can be manipulated. Of course you can always use an array for the sequence of keys of a map. – Bergi Jun 01 '20 at 16:52
  • @Bergi Thanks! You gave me an excellent idea – Jørgen Tau Jun 01 '20 at 17:51

0 Answers0