DEV Community

Cover image for Array Methods in JS - sort()
Shubham Tiwari
Shubham Tiwari

Posted on • Edited on

Array Methods in JS - sort()

Hello Guys today i will be discussing about Javascript Array sort() method.
Sorting is a process in which we sort the elements of array either in ascending order or in descending order.

Let's get started...

Example 1 - String based array sorting

const stringArray1 = ["HTML","CSS","Javascript","React JS","Bootstrap"];

const stringArray2 = ["HTML","css","Javascript","React JS","bootstrap"];

console.log(`Array 1 after sorting - ${stringArray1.sort()}`)
console.log(`Array 2 after sorting - ${stringArray2.sort()}`)
Enter fullscreen mode Exit fullscreen mode

Output -

Array 1 after sorting - Bootstrap,CSS,HTML,Javascript,React JS
Array 2 after sorting - HTML,Javascript,React JS,bootstrap,css
Enter fullscreen mode Exit fullscreen mode
  • We get the sorted arrays and there's nothing complicated in first array sorting but you can see in second array "bootstrap" and "css" came in last even though they start with "b" and "c" which came before "H" for "HTML". Let me explain you this with example below
const UPPERCASE = "A";
const lowercase = "a";

console.log(`Character Code of A - ${UPPERCASE.charCodeAt(0)}`)
console.log(`Character Code of a - ${lowercase.charCodeAt(0)}`)
Enter fullscreen mode Exit fullscreen mode

Output -

Character Code of A - 65
Character Code of a - 97
Enter fullscreen mode Exit fullscreen mode
  • As you can see the character code of "A" comes before "a" and in sort method for strings , the character code is compared that's why UPPERCASE alphabets come first while sorting the array than lowercase alphabets.

Example 2 - Number based Sorting

const numberArray = [5,4,3,2,10];

console.log(numberArray.sort())
Enter fullscreen mode Exit fullscreen mode

Output -

[ 10, 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode
  • We applied the sort method but wait why 10 came before every other number even it is bigger than all of them?
  • Well the reason behind it is in javascript sorting is done alphabetically character by character so,"10" comes before "5" because "1" in "10" is smaller than "5".
  • I will show you how to fix this in the example below
const numberArray = [5,4,3,2,10];

console.log(numberArray.sort(
  (a,b) => {
    return a-b
 }))
Enter fullscreen mode Exit fullscreen mode

output -

[ 2, 3, 4, 5, 10 ]
Enter fullscreen mode Exit fullscreen mode
  • Well it works like this -
    if a = 2 b = 10 , then a-b = 2-10 = -8 meaning b is bigger than a
    if a = 5 b = 4 , then a-b = 5-4 = 1 meaning a is bigger than b

  • If you want to sort in descending order then simply replace "a - b" to "b - a" in the arrow function.

Example 3 - Array of Objects


const arrayObject = [
  {
    name:"Shubham",
    age:21
  },
  {
    name:"Shivam",
    age:25
  },
  {
    name:"Abhishek",
    age:20
  }
]

console.log("Sort by Age")
console.log(arrayObject.sort(
 (a, b) => a.age - b.age)
 )


console.log("Sort by Name")
console.log(arrayObject.sort(
 (a, b) => a.name > b.name ? 1 : -1)
 )

Enter fullscreen mode Exit fullscreen mode
  • So what we are doing here is just like we sort the array of numbers , similarly we are doing the same with array of objects.
  • Here " (a, b) => a.name > b.name ? 1 : -1)" compares the names and return 1 or -1 based on the condition is true or false.
  • Here "a.age - b.age" applies the sorting based on age in ascending order .
  • If you apply sort() method directly on array of objects , it will return the array as it is.

Example 4 - Array of Arrays (2d array)

const arrayofArray = [[7,8,9],[1,2,3],[40,50,60]]
console.log(arrayofArray.flat(2).sort(
  (a,b) => {
    return a-b
  }))
Enter fullscreen mode Exit fullscreen mode

Output -

[
  1,  2,  3,  7, 8,
  9, 40, 50, 60
]
Enter fullscreen mode Exit fullscreen mode
  • So what we are doing here is we first flat the 2-d array into 1-d array using flat() method then applies the sort() method on it.

Example 5 - Mixed Array-

const mixedArray = ["A","B","C",1,2,3,[40,5,6],[{name:"Shubham",age:21}],true,false,null,undefined,NaN]

const mixedArray = ["A","B","C",1,2,3,[400,5,6],[{name:"Shubham",age:21}],true,false,null,undefined,NaN]
console.log(mixedArray.sort(
  (a,b) => {
    return a-b
  }))

console.log("Automatic sorting")
console.log(mixedArray.sort())

console.log("Manual sorting")
console.log(mixedArray.sort(
  (a,b) => {
    return a-b
  }))
Enter fullscreen mode Exit fullscreen mode

Output -

Automatic Sorting
[
  1,
  2,
  3,
  [ 40, 5, 6 ],
  'A',
  'B',
  'C',
  NaN,
  [ { name: 'Shubham', age: 21 } ],
  false,
  null,
  true,
  undefined
]

Manual Sorting
[
  'A',
  'B',
  'C',
  false,
  null,
  1,
  2,
  3,
  [ 400, 5, 6 ],
  [ { name: 'Shubham', age: 21 } ],
  true,
  NaN,
  undefined
]
Enter fullscreen mode Exit fullscreen mode
  • As you can see we have a sorted array of our mixed array and we can see which item of which datatype came first and which came after it.
  • But we get different result when we apply manual comparing.
  • Here is a task for you , read the output and try to get the logic of why the array is sorted like this.

I am going to end this blog here because there can be sooooo many types of arrays we can create and perform sorting on them and i can't discuss them all here so , try to implement those on your own and mention the results in the comment section.

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl

Top comments (5)

Collapse
 
waleed_ala3ser profile image
waleed-alaaser

good article

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Thank you

Collapse
 
swyrik profile image
Swyrik Thupili

const numarr = [23,245,23,35,4,234];
console.log(numarr.sort());

why the above sort result in alphabetical sorting order instead of number based sorting order?

Collapse
 
swyrik profile image
Swyrik Thupili • Edited

Looks like the elements are sorted in ascending, ASCII character order. If we provide a compare function, then the elements are sorted based on the compare function.

If compareFn is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All undefined elements are sorted to the end of the array.

developer.mozilla.org/en-US/docs/W...

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

yes it converts them to string then sort that's why we need to manually pass the compare function