23
loading...
This website collects cookies to deliver better user experience
sort()
method from freeCodeCamp.sort()
method changes the position of elements in an array in ascending order (A-Z) and returns in the original array.sort()
method on an array of names.let names = ["Jack", "Christian", "Robin", "Billy", "Terry", "Michael"]
names.sort();
console.log(names)
//output: ["Billy", "Christian", "Jack", "Michael", "Robin", "Terry"]
sort()
method does not order them properly. Here's an example.let numbers = [12, 1, 5, 3, 23]
numbers.sort()
console.log(numbers)
//output: [1, 12, 23, 3, 5]
sort()
sorts elements alphabetically. A=1, B=2, C=3, D=4, E=5
alphabetically
sorted.// ["AB", "A", "E", "C", "BC"]
let numbers = [12, 1, 5, 3, 23]
numbers.sort()
console.log(numbers)
// ["A", "AB", "BC", "C", "E"]
//output: [1, 12, 23, 3, 5]
sort()
method issue with numbers. We need to use it with a compare function
. Where it will compare two sets of elements compareFunction(a, b)
.sort()
:if compare(a,b)
is less than zero, the sort()
method sorts a to lower index than b. Meaning, a comes first.
if compare(a,b)
is greater than zero, the sort()
method sorts b to a lower index than b. So, b will come first.
if compare(a,b)
returns zero then the sort()
method considers both a and b to be equal
and the position of the elements remain unchanged.
sort()
method along with the compareFunction(a,b)
let numbers = [12, 1, 5, 3, 23]
function sortNumbers(arr){
return arr.sort(function(a, b){
if(a > b) return 1
if(a < b) return -1
return 0;
})
}
console.log(sortNumbers(numbers));
//output: [1, 3, 5, 12, 23]
sort()
method can be a useful tool to sort elements in an array in ascending order. However, its important to note that when using sort()
that it orders elements alphabetically and that elements are compared as strings. This is where the compare function(a,b)
comes in to properly compare elements and returning the value that meets the condition.