Javascript Array Sort Numbers/strings/objects ascending and descending order example

In this tutorial, Learn How to sort an Array of numbers, strings, and objects in multiple ways. You can check my other post on Javascript check substring exists in a String

Sorting numbers in reverse order

Let us declare an array of numbers.

let array = [9, 2, 1, 5, 6, 0];
console.log(array);

array.sort() method Sort the array in ascending order by default.

arrayNumbers = array1.sort();
console.log(arrayNumbers);

And the output:

[ 0, 1, 2, 5, 6, 9 ]

Let’s sort the numbers in reverse order i.e. descending.

sort method includes a custom call-back function and writes a logic to check if the present number compares with a past number.

let arrayNumbers = array1.sort(function (a, b) {
  return b - a;
});
console.log(arrayNumbers);

And the output:

[9, 6, 5, 2, 1, 0];

With Es6(ECMAScript2015), The same simplified using arrow functions as follows.

The code for Sorting the array in ascending order is

array.sort((first, second) => first - second);

sorting the array in descending order using the lambda functions

array.sort((first, second) => second - first);

Sorting String in reverse order

For suppose, stringArray is declared with strings.

let stringArray = ["B", "A", "Z", "Y"];

Sorting these numbers in ascending order is easy to sort and accepts call back with two arguments.

let resultArray = stringArray.sort(function (first, second) {
  return first > second ? 1 : -1;
});
console.log(resultArray);

And the output is

["A", "B", "Y", "Z"];

With ES6 syntax, using array functions, the same can be rewritten as follows.

let resultArray = stringArray.sort((first, second) => {
  first > second ? 1 : -1;
});

String array sorting in descending order as follows

let resultArray = stringArray.sort((first, second) => {
  first > second ? -1 : 1;
});

Sort Array of objects by string property

For example, An array is declared with three objects.

let objectArray = [
  {
    id: 1,
    name: "john",
  },
  {
    id: 3,
    name: "Eric",
  },
  {
    id: 6,
    name: "Franc",
  },
];

In this example, we are going to sort objects in an array with the name string property.

let resultArray = objectArray.sort((first, second) =>
  first.name > second.name ? 1 : second.name > first.name ? -1 : 0,
);
console.log(resultArray);

And the output is

[
  { "id": 3, "name": "Eric" },
  { "id": 6, "name": "Franc" },
  { "id": 1, "name": "john" }
]

Conclusion

In this post, You learned how to sort an array of different following types.

  • number array sort
  • string array srt
  • object array with multiple properties sort