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

See this example.

<script>
   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
</script>
Try it

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

← PreviousNext →