Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

73
Views
How to add an array of values to a Set

The old school way of adding all values of an array into the Set is:

// for the sake of this example imagine this set was created somewhere else 
// and I cannot construct a new one out of an array
let mySet = new Set()

for(let item of array) {
  mySet.add(item)
}

Is there a more elegant way of doing this? Maybe mySet.add(array) or mySet.add(...array)?

PS: I know both do not work

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

While Set API is still very minimalistic, you can use Array.prototype.forEach and shorten your code a bit:

array.forEach(item => mySet.add(item))

// alternative, without anonymous arrow function
array.forEach(mySet.add, mySet)
over 4 years ago · Santiago Trujillo Report

0

Here's a functional way, returning a new set:

const set = new Set(['a', 'b', 'c'])
const arr = ['d', 'e', 'f']
const extendedSet = new Set([ ...set, ...arr ])
// Set { 'a', 'b', 'c', 'd', 'e', 'f' }
over 4 years ago · Santiago Trujillo Report

0

This is IMO the most elegant

// for a new Set 
const x = new Set([1,2,3,4]);

// for an existing Set
const y = new Set();

[1,2,3,4].forEach(y.add, y);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!