Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Removing commas from an array of string numbers

I currently have an array of strings that are numbers

data.dataArr = [0: " 1,431,417 "
​​
1: " 1,838,127 "
​​
2: " 679,974 "
​​
3: " 2,720,560 "
​​
4: " 544,368 "
​​
5: " 1,540,370 "]

I am attempting to remove the commas so my data returns 0: "1431417" , 1: 1838127 ...

After removing commas I am then mapping this array to convert it to an array of numbers and not strings. But when console.logging the finalArray that should return an array of numbers I am getting NaN I believe this is due to the part of removing the commas.

Here is my code:

let data = {
  dataArr: [
  " 1,431,417 ",
    " 1,838,127 ",
    " 679,974 ",
    " 2,720,560 ",
    " 544,368 ",
    " 1,540,370 "
  ]
};

//removing commas
let arrData = data.dataArr.map(e => e.replace(/(,\s*)+/, ','));
let finalArr = arrData.map(Number);
console.log(finalArr)

alternatively I've tried :

let arrData = data.dataArr.replace(/,/g, "")

Which resulted in "data.dataArr.replace is not a function"

like image 997
kurtixl Avatar asked May 07 '20 15:05

kurtixl


Video Answer


3 Answers

You can use number in same map callback function, g to remove all occurrence of ,

dataArr = [" 1,431,417 ", " 1,838,127 ", " 679,974 ", " 2,720,560 ", " 544,368 ", " 1,540,370 "]

let arrData = dataArr.map(e => Number(e.replace(/(,\s*)+/g, '').trim()));
console.log(arrData)
like image 126
brk Avatar answered Oct 10 '22 14:10

brk


      ['1,234', '7,8,90,'].map(eachNo => {
return eachNo.split(',').join('')
});

Split() will split string where it will find ,(comma) and will return an array of strings.
join() will operate on array of strings.

like image 3
Vinay Jadhav Avatar answered Oct 10 '22 15:10

Vinay Jadhav


There also seems to be a space in your array which would be giving NaN, Remove everything other than digits and maybe a dot.

Try this regex:

e.replace(/[^\d.]/g, '');
like image 2
Ashish Ranjan Avatar answered Oct 10 '22 16:10

Ashish Ranjan