Tush
Tush

Reputation: 7

Pushing out random number in array format in javascript

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;
}

Upvotes: 0

Views: 94

Answers (3)

jo_va
jo_va

Reputation: 13963

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));

Upvotes: 0

tam.dangc
tam.dangc

Reputation: 2032

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()

Upvotes: 1

Promise Tochi
Promise Tochi

Reputation: 61

You can do

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

Upvotes: 0

Related Questions