Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

345
Vistas
return a string where each digit is repeated a number of times equals to its value

I'm trying to solve a problem: Given a string made of digits [0-9], return a string where each digit is repeated a number of times equals to its value. I did the repetition of numbers, how next - I don’t know.

function explode(s) {
  for (let i=0; i < s.length; i++){
    let y = s[i].repeat(s[i]);
    
    console.log(y);
  }
}
over 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Javascript is good at coercing numbers to string and vice versa but I prefer to make clear when a numerical character is being treated as a number and when it is intended to be a string.

My snippet tests processing of numbers, string representations of numbers, strings having mixtures of number and letter characters, and letter strings.

it makes use of array.split() to for the character array, array.map() to process the characters (including parseInt to formally change the character to a number when used as the argument the string.repeat(), and array.join() to return the desired numeric string after processing:

let number = 6789;
let numberString = "12345";
let badNum = "3bad2Number";
let noNum = "justLetters";

console.log(expandNums(number));
console.log(expandNums(numberString));
console.log(expandNums(badNum));
console.log(expandNums(noNum));

function expandNums(numOrString) {
  let numString = numOrString.toString();
  let chars = numString.split('');
  let processed = chars.map(char => char.repeat(parseInt(char)));
  
return processed.join('');
} // end function expandNums

The function performs well under all use situations tested, so is unlikely to throw an error if a bad argument is passes. It also does a good job with the mixed letter/number example.

over 4 years ago · Juan Pablo Isaza Denunciar

0

You were only missing a result string to collect the parts

function explode(input) {
  let result = '';
  let s = input.toString();  // So that input can also be a number
  for (let i=0; i < s.length; i++){
    let y = s[i].repeat(s[i]);
    result += y;
  }
  return result;
}
over 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Asistente virtual