Sobes.tech
Junior

How to sort an array of numbers in ascending order?

sobes.tech AI

Answer from AI

// Sorting an array of numbers in ascending order using the sort method
const numbers = [5, 2, 8, 1, 9, 4];

numbers.sort((a, b) => a - b); // Sorting the array in ascending order

// Sorted result: [1, 2, 4, 5, 8, 9]

The sort() method in JavaScript sorts array elements as strings by default. To correctly sort numbers in ascending order, you need to pass a comparison function (a, b) => a - b. This function returns a negative number if a is less than b, a positive number if a is greater than b, and zero if they are equal. This allows the sort() method to correctly determine the order of elements.

How to sort an array of numbers in ascending order… - sobes.tech