18

Is there like a quick way to get Javascript Map values as an array?

const map:Map<number, string> = new Map()
map.set(1, '1')
map.set(2, '2')

And then something like Array.from(map.values()) would give ['1','2'] ... I could have sworn that I've something like this...?

6
  • 3
    [...yourMap.values()] Commented Aug 16, 2020 at 21:24
  • It's an iterator ... Commented Aug 16, 2020 at 21:26
  • 1
    What you suggested in your question works as well: Array.from(map.values()) Commented Aug 16, 2020 at 21:26
  • 1
    @Ole map.values() is an iterator. [...someIterator] is an array. Commented Aug 16, 2020 at 21:27
  • @Paul - OK I LIKE ... - Thanks! Commented Aug 16, 2020 at 21:33

2 Answers 2

28

It is working fine. Array.from can take an iterable value as well.

const map = new Map;

map.set(1, '1');
map.set(2, '2');

console.log(Array.from(map.values()));

Sign up to request clarification or add additional context in comments.

Comments

11

Another alternative could be using Spread syntax (...).

const map = new Map().set(4, '4').set(2, '2');
console.log([...map.values()]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.