user17365408
user17365408

Reputation:

Typescript - getting map keys by its values

I have a Map<string, boolean>. I want to extract the keys to an array based on their values. I want to end up with two string arrays; one being keys whose values are false and one being keys whose values are true.

I tried to filter them like this:

const trueKeys = [...myMap.entries()].filter(it => it[1] === true).map(it => it[0]);
const falseKeys = [...myMap.entries()].filter(it => it[1] === false).map(it => it[0]);

But it requires iterating over the entries twice for each array. Is there a better way to achieve this?

Upvotes: 1

Views: 777

Answers (1)

jcalz
jcalz

Reputation: 329198

I don't think iterating over a map's entries twice vs once is a big deal, as it's hard for me to imagine a situation where changing that would make the difference between code that performs poorly and code that performs well (like running away from a tsunami; you're either too close or far enough away, and running is almost certainly not changing that).

Still, if you want to traverse only once, you can do so:

const trueKeys: string[] = [];
const falseKeys: string[] = [];
myMap.forEach((v, k) => (v ? trueKeys : falseKeys).push(k));
console.log(trueKeys, falseKeys);

Here I'm iterating the Map just once, with the forEach() method. Even [...myMap.entries()] iterates the array once before you even try to filter it, so I've avoided this to ensure that we're only traversing once.

And in the callback I push() each key into one of two arrays depending on the value. This mutates the output arrays, and you can rewrite not to do so, but then you'd almost certainly be throwing away the modest amount of performance gained.

Playground link to code

Upvotes: 1

Related Questions