Wednesday, 9 December 2020

Manipulate Array.Sort() in JavaScript

 Array.Sort() :

You might think you know JavaScript array method. Yes, of course you know. Simplest method Array.sort() will sort an array. But that's not the case actually. This method will work as expected with string array. But that's not the case with number array. Let's understand with the example.

Example of sort() on string array :

let colors = ['Black' , 'Aqua' , 'Beige' , 'Gray' , 'Cyan' , 
'DarkCyan' , 'Magenta' , 'Green' , 'LemonChiffon', 'Lime' , 
'Purple' , 'Violet']

colors.sort();
console.log(colors);

Output on console :

array(9) ["Aqua", "Black", "Blue", "Brown", 
"Chocolate", "Coral", "Crimson", "DarkBlue", "DarkGrey"]

We can notice that colors are sorted as per alphabetical order.

Example of sort() on number array :

let numbers = [10, 40, 12, 14, 150, 265, 5, 60, 7, 8, 9];
numbers.sort();
console.log(numbers);

Output in console :

array(11) [10, 12, 14, 150, 265, 40, 5, 60, 7, 8, 9]

Here, we can see that array is not sorted. Why does this happen?

Because comparison is done character-wise(digit-wise). The numbers are first converted to strings and then compared.

The numbers 10, 12, 14, 150 all starts with 1 which is smaller than any other number. Also 2 is smaller than 4,5,6,8,9 that's why we got 265 before 5,7,8,9 (any single digit number ) which is far smaller than 265. Here the sorting is done as per the Unicode order.

Thus, we have understood how we get the output for sort() in a number array. But what if we want the output to be in the conventional manner i.e. in ascending order. For that we've compare function

Using the parameter with compareFunction :

The sort method accepts one parameter "compareFunction", which is optional. When this parameter is not passed, sort() does the sorting in the above mentioned manner. To do the sorting in the conventional manner we have to pass the compareFunction parameter to the function sort.

function compareFunction(a, b) {
       return a - b;
}
numbers.sort(compareFunction);
console.log(numbers);

Output in console :

array(11) [5, 7, 8, 9, 10, 12, 14, 40, 60, 150, 265]

compareFunction works in following manner :

The compare function compares all the values in the array, two values at a time (a, b).

When comparing 40 and 150, the sort() method calls the compare function(40, 150).

The function calculates 40 - 150 (a - b), and since the result is negative (-60), the sort function will consider 40 as a value lower than 100. i.e. a is lower than b.

If the result is positive, then consider b is lower than a. Example, 150-40 (a-b)

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

In this way, the array is sorted in ascending order. To sort it in descending order we must return b - a from the compareFunction().

The Fisher Yates Method

array.sort(), is not accurate, it will favor some numbers over the others.

The most popular and correct method is called the Fisher Yates shuffle, and was introduced in data science as early as 1938!

In JavaScript, this method can be translated to this:

let numbers = [10, 40, 12, 14, 150, 265, 5, 60, 7, 8, 9];

for (var i = numbers .length -1; i > 0; i--) {
 var j = Math.floor(Math.random() * i)
  var k = points[i]
  points[i] = points[j]
  points[j] = k
}

This was all about sorting the number array in JavaScript. Hope it was helpful to you:)

Have a nice day!

No comments:

Post a Comment