Using the reduce method

Hello everyone, i have an integer of more than 2 numbers. I want to multiple the numbers together and keep mutliplying them until i have only one digit, you can see the code below, as well as what should the result be.

I tried using reduce() method but i couldn’t figure out how to multiply until i have one digit left only.

const persistence = number => {
  const array = String(number).split("");
let multiply = 0;
return array.reduce((accumulator, currentValue) => {
     multiply = accumulator * currentValue;
    return multiply;
  },)
};

console.log(persistence(999)); // 4
// because 9*9*9=729, 7*2*9=126, 1*2*6=12, and finally 1*2=2

console.log(persistence(93)); // 3
// because 9*3=27, 2*7=14, 1*4=4 and 4 has only one digit

console.log(persistence(5)); // 0
// because 5 is already a single-digit number

reduce alone is not able to do that, you need to use probably recursion or something more complex

or also a loop and reduce, but reduce alone is not enough

Apologies for this, I’ve changed the title of your post, and removed the link to the other challenge

1 Like

This can’t work, you’re missing an entire step. You want the product of an array of numbers, so sure can use reduce for that. There are a couple of minor issues with your code:

  • in your persistence function is create an array of strings. Because JS will cerce them to numbers when you try to multiply, this works, but it’s not great.
  • the variable you’ve defined, multiply is irrelevant, it does nothing. You’re immediately overwriting it with the multiplication.

So it’s exactly the same as:

[1,2,3].reduce((acc, n) => acc * n)

1•2 = 2, then 2•3 = 6, result is 6.

But this doesn’t give you what you want for every number, you need a loop, as @im59138 says. Get the product of the digits, check the number of digits, run again if there’s more than one, and so on.

Then what you’ve said should happen doesn’t make any sense.

This means the answer to every single input is 0: you don’t need to do any sums. Assuming every input will eventually result in a single digit (is that correct?), and a single digit should return 0, then just return 0, you don’t need to do any maths.

I guess you meant to say 5 for persistence(5)? As it is, the majority of the answers should be 0, but anyway

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.