JavaScript's Built-in sort Method

JavaScript's Built-in sort Method

The sort Method:

The sort method is designed to sort elements within an array in ascending order by default. The basic syntax is:

array.sort();        
sort method modifies the original array in place, meaning it directly alters the array rather than creating a new one.

Sorting Strings:

String sorting is just as effortless with the sort method. Take a look at the following example:

const fruits = ["apple", "banana", "kiwi", "cherry", "fig", "date"]; fruits.sort(); 
console.log(fruits);        

Executing this code gives the following output:

["apple", "banana", "cherry", "date", "fig", "kiwi"]        

Sorting Numbers:

For sorting the numbers, we can't only use .sort(). Let's see why...

Let's say we want to sort the given array.

const numbers = [4, 21, 8, 1, 6, 34]; 
numbers.sort(); 
console.log(numbers);        

The output of this code is as follows:

[1, 21, 34, 4, 6, 8]        
By default, the sort method treats values as strings when comparing them.

This can lead to unexpected results when sorting numbers that have different lengths, like 1, 21, 34, 4, 6 and 8.

So, here comes The Power of Comparators!!!

To handle numeric values correctly, we can provide a custom comparator function that converts the values to numbers during comparison.

The comparator function takes two arguments, typically referred to as a and b, which represent two elements from the array. The comparator function should return a value that dictates the relative order of these two elements. Here's how the comparator function is structured:

function comparator(a, b) { 
// Custom comparison logic goes here 
// Return a negative value if a should come before b 
// Return a positive value if a should come after b 
// Return 0 if a and b are considered equal in terms of sorting }        

Let's do the sorting using comparator method for the previous number array

  • Sort in ascending order

const numbers = [4, 21, 8, 1, 6, 34]; 
number.sort(ascending);
function ascending(a,b){
  return a-b;
}
console.log(numbers)        
[1, 4, 6, 8, 21, 34]        

  • Sort in descending order

const numbers = [4, 21, 8, 1, 6, 34]; 
number.sort(descending);
function descending(a,b){
  return b-a;
}
console.log(numbers)        
[34, 21, 8, 6, 4, 1]        

Sorting array of objects

Arrays of objects can be sorted by comparing the value of one of their properties.

const items = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic", value: 13 },
  { name: "Zeros", value: 37 },
];

// sort by value
items.sort((a, b) => a.value - b.value);

// sort by name
items.sort((a, b) => {
 
  if (a.name < b.name) {
    return -1;
  }
  if (a.nameA > b.name) {
    return 1;
  }
  else{
    return 0;
   }
});        

The comparator function (a, b) => {...} compares objects a and b based on their name property. Here's how it works:

  • The if (a.name < b.name) condition checks if the name of object a is alphabetically smaller (comes before) than name of object b. If true, it returns -1, indicating that a should come before b.
  • The if (a.name > b.name) condition checks if the name of object a is alphabetically larger (comes after) than name of object b. If true, it returns 1, indicating that b should come before a.
  • If neither condition is met (i.e., the names are equal), it returns 0, signifying that the order of a and b should remain unchanged.


In summary, comparators provide a flexible and powerful way to sort arrays of complex objects, allowing you to tailor the sorting logic to your specific needs. By understanding how to use comparators effectively, you can harness the full potential of the sort method in JavaScript to efficiently manage and organize your data.

Happy Coding!!

Rishabh Panesar

SDE @Symx.AI | Full Stack Developer | Ex - @Ripik.AI

1 年

Great article! Sagarika Sahoo This will be very helpful for devs who have just entered the world of JS! ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了