Tutorial on creating an array from a string of numbers.
Lets say we want to create an array from a string of numbers ("1 9 3 4 -5"). We could use two things to do so:
Lets say we want to create an array from a string of numbers ("1 9 3 4 -5"). We could use two things to do so:
Array.from()
var strNum = ("1 9 3 4 -5");
var arrNum = Array.from(strNum);
The idea here is good and it should work but we end up with an array that looks like this:
arrNum = ["1", " ", "9", " ", "3", " ", "4", " ", "-", "5"];
It is not ideal, since we have an array containing spaces and negative numbers lost their minus sign.
split()
Let's see how we can do that by using the split() method:
var strNum = ("1 9 3 4 -5");
var arrNum = strNum.split("");
Once again we will end up with an array separating all the spaces and minus signs:
arrNum = ["1", " ", "9", " ", "3", " ", "4", " ", "-", "5"];
However, we can easily fix that issue by adding a space between the quotes:
var arrNum = strNum.split(" ");
arrNum = ["1", "9", "3", "4", "-5"];
Now we have an exact representation of our string in an array and we can manipulate it anyway we need or want to such as sorting it, summing it up, extracting or replacing a specific item etc..
Comments
Post a Comment