Convert Number to Digit Array

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert a number into an array of its digits, removing its sign if necessary. We will use a combination of JavaScript's built-in methods, such as Math.abs(), spread operator (...), Array.prototype.map(), and parseInt() to achieve this. By the end of this lab, you will have a better understanding of how to work with numbers in JavaScript and manipulate them to suit your needs.

How to Digitize a Number

To digitize a number in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Math.abs() to remove the sign of the number.
  3. Convert the number to a string and use the spread operator (...) to create an array of digits.
  4. Use Array.prototype.map() and parseInt() to convert each digit to an integer.

Here's the code for the digitize function:

const digitize = (n) => [...`${Math.abs(n)}`].map((i) => parseInt(i));

Example usage:

digitize(123); // [1, 2, 3]
digitize(-123); // [1, 2, 3]

Summary

Congratulations! You have completed the Digitize Number lab. You can practice more labs in LabEx to improve your skills.