Javascript Sorting Numbers and String Using Sort Method
Learn how to javascript sorting numbers and string using sort method
Published
- Javascript Sorting small Alphabets
- Javascript Sorting Capital Alphabets
- Javascript Sorting Alphabets
- Javascript localeCompare() Function
- Javascript Sort Numbers
Javascript Sorting Small Alphabets
Sorting is really interesting when it comes to javascript. Javascript provides sort method from its core builtin methods. You can easily sort numbers and string.
Let’s start with our first examples of sorting alphbets. You can exexcute the example to play with result.
<div id="result"></div>
<script>
var letters = ["w", "z", "b", "a", "e", "g", "j", "i", "s"];
letters.sort();
document.getElementById("result").innerHTML = letters;
</script>
Javascript Sorting Capital Alphabets
Now Let’s see the same example with capital letters. You can exexcute the example to play with result.
<div id="result"></div>
<script>
var letters = ["W", "Z", "B", "A", "E", "G", "J", "I", "S"];
letters.sort();
document.getElementById("result").innerHTML = letters;
</script>
Javascript Sorting Alphabets
Now Let’s combined smalls and capital letters. You will find that sort() method not work as expected with with small and capital letters.
<div id="result"></div>
<script>
var letters = ["w", "z", "b", "a", "E", "G", "J", "I", "S"];
letters.sort();
document.getElementById("result").innerHTML = letters;
</script>
To fixed the problem we just faced with sort() method when it comes with small and capital letters we can use localeCompare.
Javascript localeCompare() Function
The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
<div id="result"></div>
<script>
var messages = ["sum", "add", "sub", "abc",
"multiply", "divide", "joker", "number", "tricky"];
messages.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
document.getElementById("result").innerHTML = messages;
</script>
Javascript Sort Numbers
Now let’s use numbers with sort() method. When we use sort with number it doesn’t work as expected. Let’s try the following example.
<div id="result"></div>
<script>
var numbers = [8000, 1000, 3000000, 99, 3544];
numbers.sort();
console.log(numbers); // [ 1000, 3000000, 3544, 8000, 99 ]
</script>
To fix how sort() method is dealing with numbers we need to provide a compare method.
<div id="result"></div>
<script>
var numbers = [8000, 1000, 3000000, 99, 3544];
numbers.sort(function(a,b){ return a-b; });
console.log(numbers); // [ 99,1000,3544,8000,3000000 ]
</script>