How do I join this numbers together?

function expandedForm(num) {
    let len = num.toString().length;
    let n = num.toString().split("");
    let result = "";

    for (let i = 0; i < len; i++) {
        result += n[i] + "0".repeat(len -1 -i).join(" + ");
    }

    return result;
}

What I am trying to do is to separate numbers like this:

1220 = “1000 + 200 + 20”

221 = “200 + 20 + 1”

I have written the code (not the perfect one) where it gets me all the necessary values but I struggle with joining them together with “+”. I tried using .join() but it did not work.

Answer

Although there are a variety of approaches, here are some general tips for you:

  • Probably don’t want to output a 0 term unless the input number is exactly 0 (only a leading 0 term is relevant, because it will be the only such term)
  • str.split('') can also be [...str]
  • No need to split a string into an array to access a character str.split('')[0] can also be just str[0]
  • Might want to assert that num is a whole number.
  • Make sure you provide enough test cases in your question to fully define the behaviour of your function. (How to handle trailing zeros, interstitial zeros, leading zeros, etc. Whether the input can be a string.)

function expandedForm(num) {
  const s = num.toString();
  const n = s.length - 1;
  const result = [...s]
    .map((char, index) => char + '0'.repeat(n - index))
    .filter((str, index) => !index || +str)
    .join(' + ');

  return result;
}

console.log(expandedForm(1220));
console.log(expandedForm(221));
console.log(expandedForm(10203));
console.log(expandedForm(0));
console.log(expandedForm(2n**64n));