Essentially I'm trying to turn an array of numbers into a string, and then back into an array of numbers (exactly like the original array that was passed in) within a single function.
I know that this will turn an array of numbers into a string:
function arrayToStringAndBack (array) {
return array.join(" ");
}
console.log(arrayToStringAndBack([1, 2, 3, 4]));
1 2 3 4
But now, if I want to turn that string back into an array, this will return the array with quotes around each number (as an array of string-numbers):
function arrayToStringAndBack (array) {
let string = array.join(" ");
return string.split(" ");
}
console.log(arrayToStringAndBack([1, 2, 3, 4]));
[ '1', '2', '3', '4' ]
What I want to do is turn this string 1 2 3 4 into an array of numbers [1, 2, 3, 4].
My idea was to iterate over each element in the string, turning the element into a number using .parseInt(), and then pushing that number into a new array:
function arrayToStringAndBack (array) {
let string = array.join(" ");
let newArray = [];
for (let i = 0; i <= string.length; i++) {
let number = parseInt(string[i]);
newArray.push(number);
}
return newArray;
}
console.log(arrayToStringAndBack([1, 2, 3, 4]));
But as you can see this logs:
[ 1, NaN, 2, NaN, 3, NaN, 4, NaN]
Why is every other element in numbers NaN? That does not make sense to me.
string.split(" ").map(Number)parseInt(" ")?