
Return om(numStr, (digit) => (digit = '-') ? '-' : Number(digit)) Īdd a Leading Digit to Represent the SignĪdding a leading digit to represent the sign means that in the resulting array, the first element can be used to represent the sign (i.e. 3: convert string to array of numeric strings, and You can also rewrite this using the om() method which would help you combine the step related to using () and () (as the first argument to om() is split into an array, and the second argument is called on every element of the array): 4: convert each array item to an integer (and add '-' as is if present) 3: convert string to array of numeric strings

1: check if number (or numeric string) Use () to iterate over each array item and convert each numeric string to a number using Number, and check for '-' explicitly (to add it as is).Convert string to an array of numeric string characters using ().

Check if value is a number (or a numeric string).If you don't do that, then you will get " Uncaught TypeError: Cannot read property 'map' of null" error.Īdding the minus sign ( -) as a string means that in the resulting array, if the original number is negative, the first element of the array will have the minus sign as a string: Since the match() method returns null on failure and an array of all matches on success, it is important to check whether the result is indeed an array before using map(Number) to convert the array of numeric string to an array of integers. Please note that the g flag used with match is important here because it returns all results matching the regular expression. Return Array.isArray(strArr) ? strArr.map(Number) : Ĭonsole.log(numToArray(12345)) // Ĭonsole.log(numToArray(-12345)) // įollowing are a few examples of the return values from this function when string values are passed in:Ĭonsole.log(numToArray('12345')) // Ĭonsole.log(numToArray('-12345')) // 3: if match found, convert each item to an integer, else return `` 2: use regex to match '-' (optionally) and numbersĬonst strArr = String(num).match(/-?\d/g) Otherwise, use () to convert each array item to an integer, by passing Number as an argument to it. Return empty array when no match is found (i.e.Convert string to an array of numeric strings using a regular expression with ().To convert an integer (positive or negative) in this way, to an array of digits, you can follow these steps: Making the most significant digit negative means that in the resulting array, if the original number is negative, the first digit will have the negative sign: Add a Leading Digit to Represent the Sign.Make the Most Significant Digit Negative.

For example, following are a few options: However, the complication arises with negative integers, specifically in how you add the negative sign ( -) to the resulting array. Converting positive integers to an array of digits is fairly straightforward.
