Introduction
You might have guessed from the title what I'm going to talk about in this post. Sorting is one of the most popular and often used methods.
Sort() method sorts the elements of an array and returns an array in a specific sorted format.
Take a look at the following example.
let animals = [ "Zebra", "Bear", "Kangaroo", "Giraffe", "Lion", "Tiger", "Dog" ];
animals.sort();
console.log(animals);
// Output : ['Bear', 'Dog', 'Giraffe', 'Kangaroo', 'Lion', 'Tiger', 'Zebra']
Oh! That's super easy 😄!
Now take a look at the following example.
let numbers = [ 1 , 50, 101 , 4 , 90 , 40 , 1000, 78 , 9 ];
numbers.sort();
console.log(numbers);
// Expected Output : [1, 4, 9, 40, 50, 78, 90, 101, 1000]
// Actual Output : [1, 1000, 101, 4, 40, 50, 78, 9, 90]
Oh wait!😳 What did we get here?
Let's find out!🧐
From observation, one thing is clear that if the array contains the elements with string data type only, they are being sorted in ascending order.
Basically, what happens behind the scene is each element in an array is converted into string and then UTF-16 code equivalent value of them are compared.
Just to make it simple, look at the following diagram :
Now we get to know that why in the second example the output was so wierd.
Because we were not aware about the things happening under the hood.
Sort with Compare function
Also, there is an another form wherein sort methods can accept a callback function which is known as compare function
The compare function accepts two parameters ( e.g a & b ), and compare these two values.
If it is returning positive integer then it places b before a.
If it is returning negative integer then it places a before b.
If it is returning zero then it keeps the order as it is.
- Now we will try to write a function for sorting an array which contains numbers.
Using Inline function
Using Arrow function
Using short-hand version
Return value :
- sort() method works on the principle place-in algorithm.
- It returns the reference of the original array.
That means if we try to change the returned array it will also change the original array as well.
- Take a look at the following example :
let numbers = [1, 5, 6, 7, 2, 3, 4, 8, 9 ];
let sortedArray = numbers.sort((a, b) => a - b);
console.log( " numbers : ",numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log( " sortedArray : ",sortedArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9];
// To check the same reference
console.log( numbers === soretedArray); // true
Application :
Earlier, In one of my Interviews I have been asked to write a program and the problem was :
//Given a list of non-negative integers, arrange them in such a manner that they form the largest number possible. The result is going to be very large, hence return the result in the form of a string.
// Input:
// 3 30 34 5 9
// 546 54 60 548
// Output: 9534330;
// 6054854654;
Thank you for stopping by!. If you find it useful consider sharing it. You can connect with me here : LinkedIn
Top comments (0)