5

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)
3

1 Answer 1

6

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)

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.