Javascript Array sort()

Introduction

Javascript array sort() method sorts an array in place.

It returns the sorted array.

The array is sorted in place, and no copy is made.

The default sort order is ascending by converting the elements into strings.

arr.sort([compareFunction])
  • compareFunction - Optional, a function that defines the sort order.

Return values from compareFunction(a,b):

Value Meaning
less than 0 a comes first.
0 leave a and b unchanged
greater than 0 b comes first.

Sort the array

var languages = ["CSS", "HTML", "Java", "Javascript"];
console.log(languages);/*from ww  w.j  av  a 2s .c  om*/

languages.sort();
console.log(languages);

Sort an array alphabetically, and then reverse the order of the sorted items:

var languages = ["CSS", "HTML", "Java", "Javascript"];
console.log(languages);/*from   ww w  .jav  a  2 s. c o m*/

languages.sort();
languages.reverse();
console.log(languages);

Use your own function for comparing

function compare(value1, value2) {
    if (value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {/*from  w  w w .  ja v  a  2s .  co m*/
        return 0;
    }
}
let values = [0, 1, 5, 10, 15]; 
values.sort(compare); 
console.log(values);  // 0,1,5,10,15 

To sort results in descending order:

function compare(value1, value2) {
    if (value1 < value2) {
        return 1;
    } else if (value1 > value2) {
        return -1;
    } else {/*from ww  w  .j a v a  2 s .  c o m*/
        return 0;
    }
}

let values = [0, 1, 5, 10, 15];
values.sort(compare);
console.log(values); // 15,10,5,1,0 

The compare function can be shortened and defined as an inline arrow function:

let values = [0, 1, 5, 10, 15]; 
values.sort( (a, b) => a > b ? -1 : 0); 
console.log(values);  // 15,10,5,1,0 

The sort method with function expressions:

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;//w  ww.  ja v a 2s .c  o m
});
console.log(numbers);// [1, 2, 3, 4, 5]

Arrow function expressions.

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);/*from  w w  w .j a  v a 2 s . co  m*/
console.log(numbers);// [1, 2, 3, 4, 5]

Sort objects.

var items = [/*from w  w  w.  j  a  v  a 2 s . c  om*/
  { name: 'CSS', value: 1 },
  { name: 'HTML', value: 7 },
  { name: 'Java', value: 5 },
  { name: 'Javascript', value: -2 },
  { name: 'C++', value: 3 },
  { name: 'C', value: 3 }
];

// sort by value
items.sort(function (a, b) {
  return a.value - b.value;
});

console.log(items);

// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }
  // names must be equal
  return 0;
});
console.log(items);



PreviousNext

Related