How to sort a nested array in reverse order JavaScript

← PrevNext →

I am using a combination of four different JavaScript built-in methods like "sort()", flat(), "reverse()" and join() to sort and reverse a nested array (array inside an array).

sort a nested array in reverse in javascript

Related... How to reverse a "string" and an "array" using while loop in JavaScript?

See this example.

   const arr = ['a', 'b', , 'd', , 'f', [[1, 9, , 2, 4]]];  // nested array.
    const rev = arr
      .flat(2)    // clear the empty slots (if any)
      .sort()     // sort the elements in order (ascending (or default) order)
      .reverse()  // reverse the sort order
      .join('');  // join the string (remove the commas)

    document.writeln(rev);	// Output: fdba9421
Try it

You may also like... How to "split" a string into Multiple lines in a web page using JavaScript?

Learn more about ".flat()" method with examples

Happy coding. 🙂

← PreviousNext →