9๐
Assuming you have an array in a string format, you can use the following regex to match all the decimals and then use .map(Number)
const str = "['6.35', '2.72', '11.79', '183.25']",
array = str.match(/\d+(?:\.\d+)?/g).map(Number)
console.log(array)
5๐
\d
matches only digits, itโs the short for [0-9]
. For example, in 6.35
\d+
matches 6
and then 35
separately and the dot is ignored. What you get in result is array containing those matches.
As suggested in other answers, use of match is redundant in your case and you can go with:
array.map(Number)
4๐
You could just map numbers.
var array = ['6.35', '2.72', '11.79', '183.25'],
numbers = array.map(Number);
console.log(numbers);
2๐
Map over the array with the Number
function, it will handle the conversion:
console.log(['6.35', '2.72', '11.79', '183.25'].map(Number));
If you want commas in your numbers, then you must stick with a string representation.
See this SO answer about a similar problem with ChartJS.
1๐
var num = ['6.35', '2.72', '11.79', '183.25'].map(num => Number(num));
console.log(num);
1๐
Parse the values to float :
console.log(['6.35', '2.72', '11.79', '183.25'].map(i => parseFloat(i)));
If for some reason .map()
doesnโt work just use a loop :
var array = ['6.35', '2.72', '11.79', '183.25']
var x = 0;
var len = array.length
while(x < len){
array[x] = parseFloat(array[x]);
x++
}
console.log(array)
0๐
var arr = ["6,35,2,72,11,79,183,25"]
var result=arr.map(Number);
result[]
typeof(result[])
0๐
I was having the same problem this is a solution i found
i had
x = "11,1.1,100,100,2,3333,99"
and i wanted
x = [11,1.1,100,100,2,3333,99]
hereโs my solution
x.toString().replace(/, +/g, ",").split(",").map(Number)