SuperCoolDude1337
SuperCoolDude1337

Reputation: 95

Splitting a number into an array

Alright so I'm trying to completely split a number into an Array. So for example:

var num = 55534;
var arr = []; <- I would want the Array to look like this [5,5,5,3,4] 

Basically i want to to completely split the number apart and place each Number into its own element of the array. Usually in the past i would just convert the number into a string then use the .split() function. This is how i use to do it:

num += "";
var arr = num.split("");

But this time i actually need to use these numbers, so they can not be strings. What would you guys say be the way of doing this?

Update, after the edit for some reason my code is crashing every run:

function DashInsert(num) { 

  num += "";
  var arr = num.split("").map(Number); // [9,9,9,4,6]
  for(var i = 0; i < arr.length; i++){
    if(arr[i] % 2 === 1){
    arr.splice(i,0,"-");
    }// odd
  }
  return arr.join(""); 

}

Upvotes: 1

Views: 3372

Answers (3)

Mritunjay
Mritunjay

Reputation: 25882

I'll do it like bellow

var num = 55534;
var arr = num.toString().split(''); //convert string to number & split by ''
var digits = arr.map(function(el){return +el}) //convert each digit to numbers
console.log(digits); //prints [5, 5, 5, 3, 4]

Basically I'm converting each string into numbers, you can just pass Number function into map also.

Upvotes: 0

Fengyang Wang
Fengyang Wang

Reputation: 12051

String(55534).split("").map(Number)

...will handily do your trick.

Upvotes: 5

elclanrs
elclanrs

Reputation: 94101

You can do what you already did, and map a number back:

55534..toString().split('').map(Number)
//^ [5,5,5,3,4]

Upvotes: 4

Related Questions