# javascript – which iteration approach is better? array vs recursion vs for-loop

It’s the solution to project euler’s 1st problem.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Recursion and the for-loop seem to be faster.

``````    function sumOfAllTheMultiples() {
return Array(1000)
.fill(1)
.map((v, i) => i + v)
.filter((v) => v % 3 === 0 || v % 5 === 0)
.reduce((t, v) => t + v);
}

console.time('simple')
console.log(sumOfAllTheMultiples())
console.timeEnd('simple')

function sumOfAllTheMultiplesRecursive(length, total = 0, currentIndex = 1) {
total = (currentIndex % 3 === 0 || currentIndex % 5 === 0) ? total+currentIndex: total;
return sumOfAllTheMultiplesRecursive(length, total , ++currentIndex)
}

console.time('recursive')
console.log(sumOfAllTheMultiplesRecursive(1000))
console.timeEnd('recursive')

function sf() {
let total = 0;
for (let index = 1; index <= 1000; index++) {
if(index % 3 === 0 || index % 5 === 0) {
total += index;
}
}