by @codeexamples

How to sort array of numbers in JavaScript

Home » javascript » How to sort array of numbers in JavaScript

In this example, we will learn about how to sort an array of numbers in JavaScript by using the sort() method.

Sort numbers in ascending order

const numbers = [5,56,2,5,1];
const sortAsc = numbers.sort((a,b)=>a-b);

console.log(sortAsc); // [1, 2, 5, 5, 56]

Sort numbers in descending order

const numbers = [5,56,2,5,1];
const sortDesc = numbers.sort((a,b)=>b-a);

console.log(sortDesc); // [56, 5, 5, 2, 1]

References

Learn more about the sort( ) method.