Sorting Array Elements in Javascript

Web DevelopmentJavascriptFront End Technology

JavaScript has pretty powerful inbuilt functions to sort arrays. By default, the sort method sorts elements alphabetically. For example, 

Example

let arr1 = ["Zebra", "Bear", "Tiger"];
arr1.sort();
console.log(arr1);

Output

This will give the output −

[ 'Bear', 'Tiger', 'Zebra' ]

Now let's look at an int example, 

Example

let arr1 = [1, 8, 31, 21];
arr1.sort();
console.log(arr1);

Output

This will give the output −

[ 1, 21, 31, 8 ]

This is not what we expected. This is being output because by default the sort method sorts elements alphabetically. In order to sort according to our wish, we need to provide it a compare function that it'll apply 2 arguments to determine which is bigger and which is smaller and sort accordingly. So in order to sort an integer array, you should call −

Example

let arr1 = [1, 8, 31, 21];
arr1.sort((a, b) => a - b);
console.log(arr1);

Output

This will give the output &,minus;

[ 1, 8, 21, 31 ]

This can also be used to provide which keys should be used to sort in more complex cases like sorting object arrays. For example, 

Example

let people = [{
   name: "Zoe",
   age: 35
}, {
   name: "Richard",
   age: 21
}, {
   name: "Agnes",
   age: 25
}];
people.sort((a, b) => {
   let nameA = a.name.toUpperCase(); // ignore upper and lowercase
   let 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(people)

Output

This will give the output −

[ { name: 'Agnes', age: 25 },
{ name: 'Richard', age: 21 },
{ name: 'Zoe', age: 35 } ]

Much more complex objects can also be sorted this way. Its all about how you structure your compare function.

As you've seen that this function sorts the array in place. In order to return a new sorted array while keeping the same order in this one, you could use the following to first create a copy then apply the sort.

output

arr.slice(0).sort();
raja
Published on 26-Jun-2018 14:17:19
Advertisements