JavaScript Sorting Arrays

JavaScript Sorting Arrays

Sorting arrays in JavaScript is a commonly used task. It involves arranging the elements of an array in a particular order, either in ascending or descending order. There are several ways to sort arrays in JavaScript.

Using the sort() method

The sort() method is a built-in method in JavaScript that can be used to sort an array in place. It sorts the elements of an array in ascending order by default.


      const numbers = [6, 4, 9, 2, 8, 1];
      numbers.sort();
      console.log(numbers); // [1, 2, 4, 6, 8, 9]
    

To sort an array in descending order, you can pass a compare function to the sort() method.


      const numbers = [6, 4, 9, 2, 8, 1];
      numbers.sort(function(a, b) {
        return b - a;
      });
      console.log(numbers); // [9, 8, 6, 4, 2, 1]
    

Using the reverse() method

The reverse() method is another built-in method in JavaScript that can be used to reverse the order of elements in an array. It does not sort the elements in any particular order but simply reverses their positions.


      const numbers = [6, 4, 9, 2, 8, 1];
      numbers.reverse();
      console.log(numbers); // [1, 8, 2, 9, 4, 6]
    

Using the map() method

The map() method can also be used to sort an array. It creates a new array with the sorted elements of the original array.


      const numbers = [6, 4, 9, 2, 8, 1];
      const sortedNumbers = numbers.map(x => x).sort();
      console.log(sortedNumbers); // [1, 2, 4, 6, 8, 9]
    

Overall, there are several methods available in JavaScript to sort arrays. The choice of method depends on the specific requirements of the task at hand.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe