4

Javascript has an Array.prototype.map but there doesn't seem to be an equivalent for sets. What's the recommended way to run map on a set in Javascript?

EDIT: Adding an example as requested

users = new Set([1,2,3])

// throws an error: 
// Uncaugh TypeError: users.map is not a function
users.map(n => n*n)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
k26dr
  • 1,229
  • 18
  • 15
  • 1
    please add an example to highlight your question. – Nina Scholz Sep 04 '16 at 11:39
  • see also http://stackoverflow.com/q/31084619/1048572 or http://stackoverflow.com/q/31232415/1048572 – Bergi Sep 04 '16 at 11:51
  • what would you like to do with the result of the calculation? a new array, a new [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)? a new [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)? – Nina Scholz Sep 04 '16 at 11:55

1 Answers1

4

You can use the

Spread-Operator

The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

on your Set to map over the Set like so.

const s = new Set([1,2,3,4]);

const a = [...s].map( n => n * 2 )

console.log(a)
Community
  • 1
  • 1
DavidDomain
  • 14,976
  • 4
  • 42
  • 50
  • You should wrap your map expression in a `Set` constructor, because mapping a `Set` should return a `Set`. The problem arises with duplicate return values though: `new Set(Array.from(s).map(n => n % 2))` yields `Set {1, 0}` - but mapping shouldn't transform the structure of the Set. –  Sep 04 '16 at 14:20