1

I've developed this codepen (http://codepen.io/PiotrBerebecki/pen/qZjojV?editors=0010) trying to solve the following JavaScript problem:

Given a non-negative integer, return an array containing a list of independent digits in reverse order. Example: 348597 => The correct solution should be [7,9,5,8,4,3]

The function below apparently is incorrect as it returns ["7", "9", "5", "8", "4", "3"] - correct order but with quotes. How could I modify it so that it returns [7,9,5,8,4,3]?

function digitize(n) {
  var initialArray = (""+n).split('');
  var reversedArray = [];
  for (var i = initialArray.length - 1; i >= 0; i--) {
    reversedArray[i] = initialArray.shift();
  }
  return reversedArray;
}
Piotr Berebecki
  • 7,428
  • 4
  • 33
  • 42

8 Answers8

10

"One-line" solution:

var num = 348597,
    arr = String(num).split("").reverse().map(Number);

console.log(arr);  // [7, 9, 5, 8, 4, 3]
  • String(num) : The String global object acts as a constructor for strings and "converts" the given number into string(in this case)

  • The Array.reverse(): method reverses an array in place

  • The Array.map(): method creates and returns a new array calling a provided function on every array element

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
5

add parseInt to convert from string to number, since when you split you turn every integer into a string

function digitize(n) {
  var initialArray = (""+n).split('');
  var reversedArray = [];
  for (var i = initialArray.length - 1; i >= 0; i--) {
    reversedArray[i] = parseInt(initialArray.shift(),10);
  }
  return reversedArray;
}

console.log(digitize(348597));
user2950720
  • 931
  • 2
  • 10
  • 26
5

Even better, reduce it to two lines:

function digitize(num) {
    return num.toString().split('').reverse().map(Number);
}

The final map call applies a function to each element in the array (in this case the function converts a string to an object) - everything else simply converts the number to a string, splits the string to an array and reverses it.

Traditionally, parseInt would be used in the map call, but this gives rise to strange behaviour.

Community
  • 1
  • 1
Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44
  • Why bother with `num = n` when `n` won't be mutated? – MDEV Mar 27 '16 at 18:00
  • You are quite correct. I was testing this out on the console, and had to create a reference as a raw value wouldn't work (I didn't wrap this in a function call) - I simply copied it out wholesale. I'll make edits. – Akshat Mahajan Mar 27 '16 at 18:04
2

Just split and reverse

var num = 348597,
    arr = num.toString().split("").reverse().map(Number);

document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

It is a simplified version of many other solutions that you can see, to deep understand how it works.

function digitize(n) {
    let correctArr = [];
    let arrOfNumbers = n.toString().split('');
    let arrOfNumbersLength = arrOfNumbers.length;
    for (let i = 0; i < arrOfNumbersLength; i++) {
        let x = arrOfNumbers.pop();
        correctArr.push(+x);
    }
    return correctArr;
}
console.log(digitize(348597));
oguz ismail
  • 1
  • 16
  • 47
  • 69
1

If you care about performance, here is the one.

var num = 348597;
var digits = num + '';
var result = [];
for (var i = 0, length = digits.length; i < length; i++) {
  result[length - 1 - i] = +digits[i];
}

console.log(result);
Lewis
  • 14,132
  • 12
  • 66
  • 87
0

For beginners who may want to see a clear format on how to solve this via plain English, this may help to understand it:

function reverseNumber(num){
    num = num + '';
        let reversedText = num.split('').reverse().join('');
        let reversedNumber = parseInt(reversedText, 10);
    console.log("reversed number: ", reversedNumber);
        return reversedNumber;
  }

console.log(reverseNumber(12345));
Jam
  • 1
  • 2
0

A simpler way to solve this is below.

function digitize(n) {
    numbers = n.toString()//convert n to a string
    arrayNum = numbers.split('') //split the string and make an array
    arrayRev =arrayNum.reverse()//reverse the new array made.
    newArr = arrayRev.map(Number) // The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.
    return newArr;
  }


  Refactored

  function digitize(n) {
   
    return n.toString().split('').reverse().map(Number) 
   }