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' ] ]
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"]],
]);