0
Q:

javascript sort array in ascending order

By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function"

numbers = [2, 3, 41, 3, 2, 4, 5];

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

// For more info on the compare function see https://www.w3schools.com/jsref/jsref_sort.asp
11

var points = [40, 100, 1, 5, 25, 10];

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

 
8
//sorts arrays of numbers
function myFunction() {
  points.sort(function(a, b){return a-b});
  document.getElementById("demo").innerHTML = points;
}
2
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
1
function myFunction() {
  points.sort(function(a, b){return a-b});
  document.getElementById("demo").innerHTML = points;
}
0
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
0

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
 
-1

New to Communities?

Join the community