Is there a way to select all values up until some key in a Map in JavaScript/Node?

Viewed 254

I have this Map will all sorts of IDs as keys and, what I would like to know, is how you can get the values of the Map up until some key is passed.

Given that you have a key, for instance '5', I would like to return 0-5 and nothing further than that. Also, keys are not ordered from 0 to infinity, I mean the index of the key in the map if that is possible.

I don't know if Map.entries() is a good use for this problem.

I'll give a little example as an array:

[
  "n89w3rn98w3",
  "67q2g76gG67",
  "vna09wa9WHD",
  "g67a3889aIU",
  "ADW78aw3a8J",
  "89a7h3aIUJ4"
]

Given that the top of the array is index 0 and the last value is index 5. If I have the key "g67a3889aIU" (4th in the array), I would like to get the following returned:

[
  "n89w3rn98w3",
  "67q2g76gG67",
  "vna09wa9WHD",
  "g67a3889aIU"
]

Which are the first 4, because it's the 4th I've inputted.

But to clarify, this should be a map, not an array. I was just giving an example.

Thanks

2 Answers

By manual:

The Map object holds key-value pairs and remembers the original insertion order of the keys.

so it means we can get key-value pairs by iterating it and recreate another Map based on order.

function takeEntriesFromMapUntilKey(mapObject, untilKey, inclusive = true) {
  const newMap = new Map();
  
  for (const [key, value] of mapObject) {
   if (key !== untilKey) {
     newMap.set(key, value);
     continue;
   }
   if (inclusive) {
     newMap.set(key, value);
   }
   break;
  }
  
  return newMap;
}

const map1 = new Map();
map1.set("n89w3rn98w3", 'data1');
map1.set("67q2g76gG67", 'data2');
map1.set("vna09wa9WHD", 'data3');
map1.set("g67a3889aIU", 'data4');
map1.set("ADW78aw3a8J", 'data5');
map1.set("89a7h3aIUJ4", 'data6');


const map2 = takeEntriesFromMapUntilKey(map1, 'g67a3889aIU');
console.log(Array.from(map2.entries()));

const map3 = takeEntriesFromMapUntilKey(map1, 'g67a3889aIU', false);
console.log(Array.from(map3.entries()));

Is something like lodash an option for you?

sample code:

const target = "g67a3889aIU";
_.takeWhile([
  "n89w3rn98w3",
  "67q2g76gG67",
  "vna09wa9WHD",
  "g67a3889aIU",
  "ADW78aw3a8J",
  "89a7h3aIUJ4"
], o => o !== target); // it will list all before g67a3889aIU then you can add it as well
Related