Split a Number into an Array in JavaScript-Code Examples

Radu TM

Split a Number into an Array in JavaScript

JavaScript by Radu TM June 22, 2022

// Split a Number into an Array in JavaScript

const splitNumber = (num) => {
  // Turn the number into a string
  const numStr = num.toString();
  
  // Declare an empty array to store the individual digits
  const digitArr = [];
  
  // Loop through the string, converting each character into a number
  // and pushing it into the array
  for (const digit of numStr) {
    digitArr.push(parseInt(digit));
  }
  
  // Return the resulting array
  return digitArr;
}

// Test it out
console.log(splitNumber(12345)); // [1, 2, 3, 4, 5]

0

16.828

Split a Number into an Array in JavaScript

JavaScript by Radu TM June 22, 2022

// split a number into an array

const splitNumber = (num) => {
  // convert number to string
  const numStr = num.toString();
  // empty array to store each digit
  const digitArr = [];
  // loop through string
  for (let i = 0; i < numStr.length; i++) {
    // convert each digit to a number and push to array
    digitArr.push(parseInt(numStr[i]));
  }
  // return digit array
  return digitArr;
}

// test
splitNumber(1234); // [1, 2, 3, 4]

0

16.828

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories