Shorter way to convert array to Set when chaining without custom functions in Javascript

Viewed 156

Consider this chain of methods that manipulates the array and results in a set:

[...Array(20).keys()]
  .filter(j => j % 3)
  .map(j => j * 5)
  .reduce((j, k) => { j.add(k); return j }, new Set())
==>
Set { 5, 10, 20, 25, 35, 40, 50, 55, 65, 70, 80, 85, 95 }

I know this can be rewritten by wrapping the chain:

new Set([...Array(20).keys()]
  .filter(j => j % 3)
  .map(j => j * 5))
==>
Set { 5, 10, 20, 25, 35, 40, 50, 55, 65, 70, 80, 85, 95 }

but that breaks the chain and forces the reader to go backwards.

Is there a way to write the last step:

  .reduce((j, k) => { j.add(k); return j }, new Set())

in a simpler way using only Javascript builtin functions and without breaking the chain?

1 Answers

You just need to use j.add(k) and that will return set itself

Set.prototype.add(value)

Appends value to the Set object. Returns the Set object with added value.

[...Array(20).keys()]
  .filter(j => j % 3)
  .map(j => j * 5)
  .reduce((j, k) => j.add(k), new Set())

To reduce the steps, you could do all of these in one go, filter and map could be replace by a reduce and 2 reduces could be combine into one (here in your case)

[...Array(20).keys()]
  .reduce((j, k) => (k % 3 ? j.add(k * 5) : j), new Set())
Related