2

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?

4
  • Why do you need the filter() and the map() when you can do all of it in the reduce()? Commented Jan 20, 2021 at 2:49
  • @charlietfl Readability for non-toy cases. I'm looking for a way to avoid the long reduce if possible. There's Array.from, I guess I'm looking for Array.into so I could do [].filter(j => j % 3).map(j => j * 5).into(new Set()) or something like that. Similar to Java's collect where you can .collect(Collectors.toSet()) Commented Jan 20, 2021 at 2:58
  • Ok but just because the chain might look cool you are creating two extra new arrays and doing more iterations than is necessary Commented Jan 20, 2021 at 3:01
  • @charlietfl Point taken about performance. I tend to prefer readability for non-critical pieces of code. Commented Jan 20, 2021 at 3:10

1 Answer 1

2

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())
Sign up to request clarification or add additional context in comments.

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.