re: Project Euler #1 - Multiples of 3 and 5 VIEW POST

FULL DISCUSSION
 

Ruby

(1...1000).select { |n| n % 3 == 0 || n % 5 == 0 }.sum
# => 233168

JavaScript

It's a shame getting a range and a sum isn't quite as easy in JS.

Array.from(Array(1000).keys())
  .filter(n => n % 3 === 0 || n % 5 === 0)
  .reduce((acc, n) => acc + n);
// => 233168
 

Or generate the range with the es6 spread operator:

[...Array(1000).keys()]
    .filter(n => n % 3 === 0 || n % 5 === 0)
    .reduce((acc, n) => acc + n)

There's also a nasty (but shorter) eval hack to use in place of reduce. You can use .join(+) to convert the array into a string containing each number joined by the '+' sign, then evaluate that string as if it's a JavaScript expression to get the sum:

eval([...Array(1000).keys()].filter(n => n % 3 === 0 || n % 5 === 0).join('+'))

It's a bad practice to use eval, of course, but useful for JS code golf.

Or with lodash:

_(_.range(1, 1000)).filter(n => n % 3 === 0 || n % 5 === 0).sum()
code of conduct - report abuse