{

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


In this tutorial, Learn to sort an Array of numbers, strings, and objects in multiple ways.

Sorting numbers in reverse order in javascript

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

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

And the output is

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

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

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

And the output is

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

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

Code for Sorting the array in ascending order is

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

sorting the array in descending order using the following

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

Sorting numbers in reverse order in JavaScript

For suppose, stringArray is declared with strings.

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

Sorting these numbers in ascending order is easy to sort 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;
});

Object Array sort by string property

For example, An array declared wit three objects.

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

this example, we are going to sort objects in array with 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
  • string array
  • object array with multiple properties

I hope you learned new things with this post.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.