0

Im trying return an int that count the last Zeros of an int, but I can´t to stop the flow of the loop when it finds something that is not zero. whats wrong?

const endZeros = (value) => {
  const stringValue = `${value}`
  const arrValue = stringValue.split("").reverse()
  let total = 0;
  arrValue.map(el => {
    if (el === "0") {
      total = total + 1
    } else {
      return // I check return false too (and true, and all! --> desesperation)
    }
  })
  return total;
}

endZeros(100100)

Thank You, everyone ❤️

1 Answers1

0

How about a simple regexp?

const lastZeros = num => { const zeros = String(num).match(/0+$/); return zeros ? zeros[0].length : 0 };

console.log(lastZeros(100100))
console.log(lastZeros(111111))
console.log(lastZeros(101000))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Wow, I'm impressed!, the truth is that I have not thought about doing it with regex, but there is something that catches my attention: the result of `const zeros = String(num).match(/0+$/);` its something like this `['0', index: 5, input: '201010', groups: undefined] ` according to `typeof` an object (array) But where does that come from? Where can I find more information about that response? very very very thank you! – Verónica MF Nov 16 '21 at 10:07
  • I am not sure what you are asking.... You are talking about the "match" object of `String(num).match(/0+$/)` – mplungjan Nov 16 '21 at 10:10
  • Sorry, I will try to explain me better, but I understand its dificult because we think in different way, I mean that I dont understand this result: `['0', index: 5, input: '201010', groups: undefined]`--> match() return this array always? – Verónica MF Nov 16 '21 at 10:19
  • Yes: it is looking for '0', found the last one in position 5, the input was 201010 and there were no (groups) defined - The assigned toString is the match. I never debug a match object. I do destruct it if I use groups – mplungjan Nov 16 '21 at 10:21