Convert Number to Digit Array

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") subgraph Lab Skills javascript/variables -.-> lab-28274{{"`Convert Number to Digit Array`"}} javascript/data_types -.-> lab-28274{{"`Convert Number to Digit Array`"}} javascript/arith_ops -.-> lab-28274{{"`Convert Number to Digit Array`"}} javascript/comp_ops -.-> lab-28274{{"`Convert Number to Digit Array`"}} javascript/higher_funcs -.-> lab-28274{{"`Convert Number to Digit Array`"}} javascript/template_lit -.-> lab-28274{{"`Convert Number to Digit Array`"}} end

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.

Other JavaScript Tutorials you may like