1

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?

2 Answers 2

3

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; }

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

Comments

1

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);

1 Comment

Swooping in with the obnoxious one-liner edition! const result = x.map(y => y.map(z => z.map(Number)))

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.