sort a list of numbers in javascript

To sort a list of numbers in JavaScript, you can use the built-in sort() method of arrays. Here's an example:

index.tsx
const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

numbers.sort(function(a, b) {
  return a - b;
});

console.log(numbers);
// Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
170 chars
9 lines

The sort() method sorts the array in place, which means that the original array is modified. The function(a, b) passed as argument to sort() is the sorting function that defines how the items in the array should be compared. In this case, it subtracts b from a (i.e. a - b), which results in ascending order. For descending order, you can simply swap a and b like this: b - a.

related categories

gistlibby LogSnag