One-liner to sort an array in ascending order in JavaScript

In JavaScript:

const sortedArray = originalArray.sort((a, b) => a - b);

This one-liner uses the built-in sort() method of an array to sort its elements in ascending order. The sort() method sorts the elements of an array in place and returns the sorted array. To specify the sort order as ascending, we pass an arrow function as an argument to the sort() method. The arrow function takes two parameters a and b, which represent two elements of the array being compared. The function returns a negative value if a is less than b, a positive value if a is greater than b, or zero if a and b are equal. By subtracting b from a in the arrow function, we ensure that the sort order is ascending.

The result of this one-liner is assigned to the sortedArray variable, which holds the sorted array in ascending order.

This one-liner is a concise and efficient way to sort an array in ascending order in JavaScript, using the built-in sort() method and an arrow function to specify the sort order. It avoids the need for a loop or conditional statements to perform the sort, and can be easily adapted to handle other types of array operations that rely on built-in methods.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: