2

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.

2
  • I recommend accepting Hao Wu's answer, it'll be more performant than mine I believe Commented Jan 4, 2021 at 1:49
  • Thanks Nick, i think you both give the great answer. But yesterday you commenting first, so i use your answer. Well, i will change it. Thanks Commented Jan 5, 2021 at 5:13

4 Answers 4

4

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, this is better than mine
@Nick They are about equal when it comes to the performance: jsfiddle.net/9evxz6rj/1 vs jsfiddle.net/9evxz6rj/0
3

One possible solution is to just do this operation on the absolute value and, during the map, check if the number was negative (only for the first index).

const number = -800;
const numberString = Math.abs(number).toString();
const arrayString = numberString.split``.map((x, i) => i == 0 && number < 0 ? -x : +x);

console.log(arrayString)

Comments

1

If you're not clear about Regex, you can use Array.from to convert a string to an array number. Then handle the first number based on the sign of original number.

console.log(convertNumberToArray(800));
console.log(convertNumberToArray(-800));

function convertNumberToArray(number){
  var result = Array.from(Math.abs(number).toString(), Number);
  result[0] *= number <= 0 ? -1 : 1;
  return result;
}

Comments

1

Use String#match with regex which matches optional - with the dig it.

var number = -800;
var numberString = number.toString().match(/-?\d/g);
var numberInt = [];

for (var i = 0; i < numberString.length; i++) {
    numberInt.push(parseInt(numberString[i]));
}
console.log(numberInt);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.