arraysflatten

I need to flatten a multi dimensional array using JS 's flat method. This is the Array [ ["1", "0"], ["3", "5", ["8", ["10"], "11"] ], ]


function flatArrs(arr) {
  let output = arr
    .flat()
    .sort((a, b) => a - b);
  console.log(output);
}

flatArrs([
  ["1", "0"],
  ["3", "5", ["8", ["10"], "11"]],
]);

This is the output and all arrays do not show flattened...why? [ '0', '1', '3', '5', [ '8', [ '10' ], '11' ] ]


Solution

  • flat() takes a depth parameter which specifies how deep to flatten, the default is 1. To flatten to an arbitrary depth you can pass Infinity.

    MDN details a number of alternatives, including using concat(), recursivity, and generator functions.

    function flatArrs(arr) {
      let output = arr
        .flat(Infinity)
        .sort((a, b) => a - b);
      console.log(output);
    }
    
    flatArrs([
      ["1", "0"],
      ["3", "5", ["8", ["10"], "11"]],
    ]);