Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Last active April 24, 2020 14:33
Show Gist options
  • Save mojaray2k/f50172d3e90018a8d21988fc1c2d320a to your computer and use it in GitHub Desktop.
Save mojaray2k/f50172d3e90018a8d21988fc1c2d320a to your computer and use it in GitHub Desktop.
Array Sort Method

Definition and Usage

TThe sort() method sorts the items of an array.

The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).

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" (See "Parameter Values" below).

Note: This method changes the original array.

Parameter Values

Parameter Values

// Sort Arrays Ascending using For loop

var myNumArray = [10,20,1,2,3];


for (var i = 0; i < myNumArray.length; i++){
  for (var j = 0; j < i; j++){
    if(myNumArray[i] < myNumArray[j]){
      var x = myNumArray[i];
      myNumArray[i] = myNumArray[j];
      myNumArray[j] = x;
    }
  }
}

console.log(myNumArray);

// Sort numbers in an array in ascending order:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});

console.log(points);

// Sort numbers in an array in descending order:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});

console.log(points);

// Get the highest value in an array:
var points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in the array in descending order
points.sort(function(a, b){return b-a}); 
// The first item in the array (points[0]) is now the highest value

// Get the lowest value in an array:
var points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in the array in ascending order
points.sort(function(a, b){return a-b});    
// The first item in the array (points[0]) is now the lowest value

console.log(points[0]);

// Sort an array alphabetically, and then reverse the order of the sorted items (descending):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits);
fruits.reverse();

console.log(fruits);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment