In order to sort an array of numbers ascending, use the sort
function:
const array = [30, 15, 6, 8, 10, 14].sort((a,b) => a - b); //[6, 8, 10, 14, 15, 30]
Sorting an array of numbers descending, using the sort
function:
const array = [30, 15, 6, 8, 10, 14].sort((a,b) => b - a); //[30, 15, 14, 10, 8, 6]
Making a copy of an array after sorting using the spread operator:
const array = [30, 15, 6, 8, 10, 14];
const sortedArray = [...array].sort((a,b) => a - b); //[6, 8, 10, 14, 15, 30]
Making a copy of an array after sorting using the slice function:
const array = [30, 15, 6, 8, 10, 14];
const sortedArray = array.slice().sort((a,b) => a - b); //[6, 8, 10, 14, 15, 30]