0

I need to get an array of distinct strings from a map, extracting the string from a property of the Map's values. At the moment, I have the following code and was wondering if there was a more elegant way to do it?

myMap   {   key1 : [{ a : “myA”, b : “myB”, c : “myC”}, {  a : “myAA”, b : “myB”, c : “myC”}],
            key2 : [{ a : “myAA”, b : “myB”, c : “myC”}, {  a : “myAAA”, b : “myB”, c : “myC”}]
        }

Ans needed = ["myA", "myAA", "myAAA"]

var ans = new Set();

for (let i of myMap.values()) {
    for (let j of i){
        ans.add(j.a);
    }
}

return Array.from(ans);
P.Ellis
  • 55
  • 2
  • 10
  • Possible duplicate of [How to get unique values in an array](https://stackoverflow.com/questions/11246758/how-to-get-unique-values-in-an-array) – Joseph D. Jun 19 '18 at 12:22

1 Answers1

0
 return [...new Set([...myMap.values()].map(el => el.a))];

Just use map to shortify it a bit.


Alternatively you could use a helper to ensure uniqueness:

const unique = (s = new Set) => el => !s.has(el) && s.add(el);

So you can just do:

return [...myMap.values()].filter(unique());
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I'm afraid this gives me an undefined returned. I don't think it takes notice of the fact that each element of values is an array as well so there are more than one el in each. – P.Ellis Jun 21 '18 at 09:19