What is a real world application of `.reduce()`?

Here’s another example taken from the narrative of “The Sieve of Eratosthenes” (a Pro offering, I believe, so you may not be able to access it). Note the return value…

const sieveOfEratosthenes = (limit) => {
  // Handle edge cases
  if (limit <= 1) {
    return [];
  }
  // Create the output
  const output = new Array(limit + 1).fill(true);
  // Mark 0 and 1 as non-prime
  output[0] = false;
  output[1] = false;

  // Iterate up to the square root of the limit
  for (let i = 2; i < Math.pow(limit, 0.5); i++) {
    if (output[i] === true) {
      // Mark all multiples of i as non-prime
      for (let j = Math.pow(i, 2); j <= limit; j = j + i) {
        output[j] = false;
      }
    }
  }

  // Remove non-prime numbers
  return output.reduce((primes, current, index) => {
    if (current) {
      primes.push(index);
    }
    return primes
  }, []);
}

Above we have an array of truth values, either true or false that has be sieved over and transformed from all true, to only some true (the ones that don’t get re-marked). In the return expression we cache only the indices where the value is true. That gives us our list of primes up to the limit.

array = [‘A’, ‘quick’, ‘brown’, ‘fox’, ‘jumps’, ‘over’, ‘the’, ‘lazy’, ‘dog’];
array.reduce((a, b) => a + ’ ’ + b)

array.join(' ')

we can use join instead of reduce.

That much is moot. The above simply demonstrates the use of .reduce. We’re not confined to one way or another, and obviously .join() makes much more sense in this case.

Where .reduce() could prove useful is if there was some logic being applied in the joining process since it has a callback function that can be expanded for that purpose.

I checked it. .reduce() is good for joining strings like ’ and ’ at last concatenaton

1 Like

Not a professional but I think it’s very useful for many score systems alike this one:

// vvv a array for tracking how much money you got in each month vvv
const moneyMonths = [3425, 4582, 7542, 7572, 3545, 7645, 4356, 3784, 6855, 8561, 2306, 5020];
const totalMoneyEarned = moneyMonths.reduce((a, b) => {
  return a + b;
});

console.log(totalMoneyEarned) // Output is the total of moneyMonths: 65193