2 Easy Ways to Split Numbers in Javascript

Split Numbers Javascript

You need to split numbers when you want to perform specific operations or manipulate the individual digits or parts of a number. There are two simple ways to split numbers in JavaScript:

1. Using String Conversion and Split

In this method, we can split the numbers into a single line and store it as an array in a variable. Before using this method, you need to understand the concepts about these three javascript in-built methods:

  1. toString()
  2. split()
  3. map()

If you don’t have any idea about this, that’s okay, I’ll tell you how it works in simple terms

toString()

This method is used to convert the number to a string. We must do this step to split the numbers into digits splitting is a string operation in JavaScript.

var a = 25;

console.log(typeof a) // number
console.log(typeof a.toString()) // string

In this example, we have stored an integer/number data type in the variable “a”. But if we invoke the variable ‘a’ with the toString() method and log it, its type has changed to string.

split()

The split() is a string representation of the number. So if we pass the empty string split('') as a parameter, it will split the string at every character, effectively separating each digit of the number into individual elements of an array. We cannot invoke this method with numbers so we can use the toString() method to convert from numbers to strings and then use the split() method, like.

var a = 25;
console.log(a)

const myArray = a.toString().split("");
console.log(myArray)

After using the split() method in the above code, the numbers are stored in the array but it is a string. To convert from string to numbers, we need to use the map() method.

READ ALSO  3 Simple Ways to Return Multiple Values in JavaScript Function

map()

The map() method is used to apply to each element of the array. For example,

var a = 25;

console.log(a)

const myArray = a.toString().split('').map(Number);
console.log(myArray) // [2, 5]

So, we can split the numbers by using this three methods, like

function splitNumber(number) {
return number.toString().split('').map(Number);
}

// Example usage:
const number = 123456789;
const result = splitNumber(number);
console.log(result); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

2. Using Array.from() method

In this method, we can split numbers using toString() and Array.from() method.

function splitNumber(number) {
const numberString = number.toString();
return Array.from(numberString, Number);
}

// Example usage:
const number = 12345;
const result = splitNumber(number);
console.log(result); // Output: [1, 2, 3, 4, 5]
  1. As done in the previous method, we first convert the numbers into strings using the toString() method
  2. Then we use the Array.from() method, it is used to create a new array from an iterable or array-like object.

Leave a Reply