Sort
The sort
method sorts the items of an array in a specific order (ascending or descending).
let city = ["California", "Barcelona", "Paris", "Kathmandu"];
let sortedCity = city.sort();
console.log(sortedCity);
// Result: ['Barcelona', 'California', 'Kathmandu', 'Paris']
To fix the sorting issue in numbers, compare functions are used. Compare functions defines ort orders and return a negative, zero, or positive value based on the arguments.
const points = [40, 100, 1, 5, 25, 10];
points.sort((a, b) => {return a-b});
// Result: [1, 5, 10, 25, 40, 100]
The sort()
method overrides the original array.
Last updated
Was this helpful?