I want to put all numbers from min to max vars as a single number to array.
So in my example I want arr = [1,4,1,5,1,6] but i get [1,4, 1,5, ,1,6] as the result.
The problem is when i put separated values in array.
Would be very greatfull for any kind of help.
let min = 14,
max = 16,
arr = [];
for (i=min; i<=max; i++) {
arrPsh = i.toString().split("");
arr.push(arrPsh);
}
for (i=0; i<arr.length; i++) {
console.log(arr[i]);
}
3
Answers
Use spread syntax to pass each digit as a separate array element:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Actually you don’t need to split the string. The spread syntax gets the default iterator for a variable, accessed with
str[Symbol.iterator]()
. In our case we have a string and its default iterator iterates characters in the string:Using
Array::flat()
would be definitely slower since it creates an intermediate array and introduces some unneeded magic of converting a wrong result to a proper one:You can flatten the array:
Just
join
andsplit
the array in the end:This will be 10x faster than other solutions.