ar2015
ar2015

Reputation: 6150

Javascript convert array of array of string to array of array of number

I am new in Javascript and I looking for the neatest way to convert

x=[[["0","0"],["1","1"],["2","1.5"]],[["0","0.1"],["1","1.1"],["2","2"]]]

into

[[[0,0],[1,1],[2,1.5]],[[0,0.1],[1,1.1],[2,2]]]

Except for using two for loops to implement this method, is there any shortcut alternative in JS?

Upvotes: 1

Views: 54

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386868

You could use a recursive approach for nested arrays.

var x = [[["0", "0"], ["1", "1"], ["2", "1.5"]], [["0", "0.1"], ["1", "1.1"], ["2", "2"]]],
    result = x.map(function iter(a) {
        return Array.isArray(a) ? a.map(iter) : +a;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Pranav C Balan
Pranav C Balan

Reputation: 115272

Use nested Array#map method.

x = [
  [
    ["0", "0"],
    ["1", "1"],
    ["2", "1.5"]
  ],
  [
    ["0", "0.1"],
    ["1", "1.1"],
    ["2", "2"]
  ]
];

var res = x.map(function(arr) {
  return arr.map(function(arr1) {
    return arr1.map(Number);
  });
})

console.log(res);


With ES6 arrow function

x = [
  [
    ["0", "0"],
    ["1", "1"],
    ["2", "1.5"]
  ],
  [
    ["0", "0.1"],
    ["1", "1.1"],
    ["2", "2"]
  ]
];

var res = x.map(arr => arr.map(arr1 => arr1.map(Number)));

console.log(res);

Upvotes: 1

Related Questions