0

How I parse array of arrays to float/int?

I have:

0: Array [ "2011", "127072,7" ]
1: Array [ "2012", "125920,3" ]
2: Array [ "2013", "129305,4" ]
3: Array [ "2014", "135364" ]
4: Array [ "2015", "136757" ]
5: Array [ "2016", "155653,5" ]
6: Array [ "2017", "164130,5" ]

And i need converted to

[[2011, 127072.7], [2012, 125920.3], [2013, 129305.4], [2014, 135364], ..... ]

So next thing is a replace , with ..

Is there some solution for this?

1
  • 1
    What have you tried? You're expected to at least try then come back if you have issues. This is not a code writing service. Commented Feb 6, 2020 at 9:39

3 Answers 3

3

Just use map method with Number constructor.

let result = array.map(arr => arr.map(item => Number(item.replace(/,/g, '.'))))

let array = [[ "2011", "127072,7" ], [ "2012", "125920,3" ]]
console.log(array.map(arr => arr.map(item => Number(item.replace(/,/g, '.')))));

Sign up to request clarification or add additional context in comments.

Comments

1

Simply use this :

var result = array.map(function(arr){

   return arr.map(function(num){
      return Number(num.replace(',' , '.'))
   })

}) 

2 Comments

This is not working because "127072,7" is converted to NaN.
Yes, i fixed it now.
0

In case you have more than one deep level, recursive solution also could helps

const arrays = [
  [
    "2017", 
    [
      "2014",
      [ "2017", "164130,5" ]
     ],
  ],
  [ "2011", "127072,7" ],
  [ "2012", "125920,3" ],
  [ "2013", "129305,4" ],
  [ "2014", "135364" ],
  [ "2015", "136757" ],
  [ "2016", "155653,5" ],
  [ "2017", "164130,5" ],
]

function formatNumber(string) {
  return +string.replace(`,`, `.`)
}

function recursiveSolution(array) {
  return array.map(item => typeof item === "string" ? formatNumber(item) : recursiveSolution(item))
}

const result = recursiveSolution(arrays)
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.