Sorting Array and Object Data in JavaScript Tutorial

Introduction

In this tutorial, I will show you How to Sort Array and Object Data in JavaScript. This tutorial's main goal is to provide the new programmer or students with a reference to enhance their programming capabilities using JavaScript. Here, I will provide some examples for sorting array and object data. An example source code that demonstrates the sorting of an array and object is also provided.

How to Sort an Array and Object in JavaScript?

In some instances, we developers might need to sort the array of data or objects on the client side in order to achieve our desired feature for the project that we are making. Using the Array.prototype.sort() method we can sort the array of data. Since this method was built for arrays, we do need to convert the object into an array first so we could use this method.

What is Array.prototype.sort() method in JavaScript?

The Array.prototype.sort() method is used for sorting an array's items while they are in the array, and the reference to the sorted array is returned. The elements are first converted to strings, and then their sequences of UTF-16 code unit values are compared to determine the default sort order, which is ascending.

Syntax

Here's the syntax of the JS sort method:

  1. array_variable.sort()

And the syntax with compare function is:

  1. array_variable.sort((firstItem, secondItem) => { return firstItem - secondItem })
  2.  
  3. //or
  4.  
  5. function comparefn(a,b){
  6. return a - n;
  7. }
  8. array_variable.sort(comparefn)

The given example above is only an example that demonstrates how to use the sort method.

In compare function, here's the guide that you must know to build your logic for sorting your array

Return Value Sort Order
=== 0 If the return value is equal to 0, the original order of the array's first and second items will be kept
< 0 If the return value is less than 0, the array's first item will sort before the second item.
> 0 If the return value is greater than 0, the array's first item will sort after the second item.

Example

Below is an example of sorting the items of an Array.

  1. var arr = ['c', 'a', 'd', 'b'];
  2.  
  3. // Sort Array Items from A-Z
  4. var sorted = arr.sort( (a, b) => {
  5. if(a > b)
  6. return 1;
  7. if(a < b)
  8. return -1;
  9.  
  10. return 0;
  11. } )
  12. console.log(sorted)
  13. /**
  14.   * Outputs : ['a', 'b', 'c', 'd']
  15.   */

Below is an example of sorting the items of an Object.

  1. var obj = {'a' : {name : 'Grapes'}, 'b' : {name:'Pear'}, 'c':{name:'Apple'}, 'd' : {name:'Orange'}};
  2.  
  3. // Sort Object Items by Name Value from A-Z
  4. var sorted = Object.keys(obj)
  5. .reduce( (arr, k) => {
  6. obj[k]['key'] = k
  7. arr.push(obj[k])
  8. return arr
  9. }, [] )
  10. .sort( (a, b) => {
  11. if((a.name).toLowerCase() > (b.name).toLowerCase())
  12. return 1;
  13. if((a.name).toLowerCase() < (b.name).toLowerCase())
  14. return -1;
  15.  
  16. return 0;
  17. } ) .reduce( (nobj, k) => {
  18. nobj[k] = obj[k]
  19. delete nobj[k]['key']
  20. return nobj
  21. }, {} )
  22. console.log(sorted)
  23. /**
  24.   * Outputs : {'c':{name:'Apple'}, 'a' : {name : 'Grapes'}, 'd' : {name:'Orange'} , 'b' : {name:'Pear'}}
  25.   */

I have also provided a simple web application that contains multiple examples that demonstrate Sorting Arrays and Objects in JavaScript. You can download the source code zip file by clicking the Download Button below the article. The sample source code contains sorting scripts for Array and Object (Ascending/Descending).

Demo Application Snapshot

JS Array Sort Method

DEMO VIDEO

That's the end of this tutorial. I hope this JavaScript Array and Object Sorting Tutorial will help you with what you are looking for and that you'll find this useful for your current and future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment