• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

247
Views
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);
  }
}
about 3 years ago · Juan Pablo Isaza
2 answers
Answer question

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.

about 3 years ago · Juan Pablo Isaza Report

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;
}
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error