0

Given a non-negative integer, return an array or a list of the individual digits in order.

digitize(n): separate multiple digit numbers into an array.

Parameters:

n: number - Number to be converted

Return value:

Array<number> - Array of separated single digit integers

Example:

n            123
Return value [1,2,3]

Here is what I have done

Function digitize(n) {
  let number =[ ];
  let stringDigi = n.tostring();

  for (let i = 0, len = stringDigi.length; i < len; i++) {
    number.push (+stringDigi.charAt(i)); 
  }

  return number;
}
2
  • 2
    n.tostring(); won't work, capitalization matters in programming Commented Mar 19, 2019 at 23:41
  • What is the question? Commented Mar 20, 2019 at 0:39

3 Answers 3

1

Just make it simple

const fn = n => n.toString().split('').map(e => parseInt(e))

console.log(fn(123))

And take care of the syntax.

function not Function

toString() not tostring()

Sign up to request clarification or add additional context in comments.

Comments

0

For non-negative integers (0, 1, ...), you can use toString() or a template string followed by split() and map(), use the + operator to turn your digit into a number:

const digitize = n => `${n}`.split('').map(x => +x);

console.log(...digitize(0));
console.log(...digitize(1234));

Another way is to use match(/\d/g) to extract the digits with a regex. This method works with all numbers without modification, except for || [] that handles non-matches when undefined/null is passed in:

const digitize = n => (`${n}`.match(/\d/g) || []).map(x => +x)

console.log(...digitize(0));
console.log(...digitize(1234));
console.log(...digitize(-12.34));
console.log(...digitize(undefined));

To make the first method work for all numbers, null and undefined, you have to add a ternary and a filter() on isNaN() values:

const digitize =
  n => n || n === 0 ? `${n}`.split('').map(x => +x).filter(x => !isNaN(x)) : [];

console.log(...digitize(0));
console.log(...digitize(1234));
console.log(...digitize(-12.34));
console.log(...digitize(undefined));

If you want to use a for loop, I suggest to use for/of. Also take care of the case when writing function and toString:

function digitize(n) {
  const number = [];
  const str = n.toString();
  for (const c of str) {
   number.push(+c); 
  }
  return number;
}

console.log(...digitize(1234));

1 Comment

The input is "non-negative integer"
0

You can do

function digitize(n) {
  return (n).toString().split("");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.