Reputation: 6150
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
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
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);
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