Search code examples
javascriptarraysarraylistnegative-numbercolumnsorting

How To Get An Array From Splitted String That Has Negative Value


I don't know what is the right question for this.

I want to make this number -800 become [-8,0,0] is anyone can build it

The first thing that I do, is to make the number become a string and using the map function I iterate it becomes an array like this

const number = -800;
const numberString = number.toString();
const arrayString = numberString.split``.map((x) => +x);

console.log(arrayString)

But the result is [ NaN, 8, 0, 0 ]

How to change the NaN and first index 8 become -8 without disturbing the other index. So it becomes [-8, 0, 0]

Is anybody can help me?

Thanks.


Solution

  • Try numberString.match(/-?\d/g) instead of split

    const number = -800;
    const numberString = number.toString();
    const arrayString = numberString.match(/-?\d/g).map(x => +x);
    
    console.log(arrayString)