{"id":1386,"date":"2024-01-14T13:52:12","date_gmt":"2024-01-14T13:52:12","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1386"},"modified":"2024-01-15T09:52:28","modified_gmt":"2024-01-15T09:52:28","slug":"sort-an-array-of-objects-in-javascript","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/sort-an-array-of-objects-in-javascript\/","title":{"rendered":"Sort an Array of Objects in JavaScript (4 Easy Methods)"},"content":{"rendered":"\n<p>Sorting means putting things in order. It is needed very often in javascript programs. In this article, we will learn how to sort an array of objects in Javascript based on specific criteria, such as numeric values, strings, or other custom properties. Let\u2019s explore this topic which will help us to effortlessly order data, contributing to code clarity and functionality.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is an Array of Objects?<\/strong><\/h2>\n\n\n\n<p><strong>An array is a collection of similar kinds of entities i.e. it consists of multiple values in a single variable. So an array of objects simply means multiple objects.<\/strong><\/p>\n\n\n\n<p>An object consists of key-value pairs where keys represent properties of that object and values denote the actual data of those properties.<\/p>\n\n\n\n<p>Here each object inside the array is a distinct entity with its own set of properties and values.&nbsp;<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/JSShe1awtIjRpfjlgNbbif83qoj0f9xCaVw0mk1_PCYKYeHLWL16RuOoKPDQQL02Y2FSwksV6nzA0Xr91BAu1VS6sufWIg8Dut-duElAjvJtQdnVuwt0tJeX5FP2XiFOQVPRR91hRB4QqMsaPcYlUXw\" alt=\"Example\"\/><\/figure>\n<\/div>\n\n\n<p>For Example, consider the following array named workers.<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>\/\/ Array of objects representing worker information\nlet workers = &#91;\n    \/\/ Object for the first worker\n    { \n        firstName: 'Advin',\n        lastName: 'Mark',  \n        age: 21,         \n        joinDate: 'December 15, 2023' \n    },\n    \/\/ Object for the second worker\n    { \n        firstName: 'Marry',    \n        lastName: 'Con',     \n        age: 23,       \n        joinDate: 'January 20, 2023'  \n    },\n    \/\/ Object for the third worker\n    { \n        firstName: 'Harry',   \n        lastName: 'Potter',   \n        age: 32,          \n        joinDate: 'February 25, 2023'\n    },\n    \/\/ Object for the fourth worker\n    { \n        firstName: 'Lily',   \n        lastName: 'Potter',   \n        age: 32,          \n        joinDate: 'June 25, 2023'\n    }\n];\n<\/code><\/pre>\n\n\n\n<p>Here an array named workers is declared. It has four objects. Each object has four properties encapsulated within it, namely firstName,lastName, age, and joinDate.&nbsp;<\/p>\n\n\n\n<p><strong>These properties can be accessed using dot notation (object.property) and this property is very important in sorting based on specific criteria.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>4 Methods to Sort an Array of Objects in JavaScript<\/strong><\/h2>\n\n\n\n<p><strong>JavaScript has a built-in Sort() method. It naturally sorts in ascending order. It works when we have to sort strings alphabetically. However, this function does not directly work on arrays of numbers or objects.\u00a0<\/strong><\/p>\n\n\n\n<p>We must pass a custom compareFunction inside the sort() method to tell how the objects should be compared and ordered. This function defines the criteria for ordering the objects within the array. It is written as:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>workers.sort(compareFunction);<\/code><\/pre>\n\n\n\n<p>This compareFunction takes two parameters in it. Let it be x and y. These are two objects we are comparing. It returns a negative, zero, or positive value based on arguments passed. If \u2018x\u2019 should be placed before \u2018y\u2019 it returns a negative value, in the case of a positive value \u2018x\u2019 is placed after \u2018y\u2019, and zero is returned if \u2018x\u2019 and \u2018y\u2019 are of the same order.<\/p>\n\n\n\n<p>Now let&#8217;s explore some examples of numerical, string, and Date values,<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1) Sorting By Numeric Values<\/strong><\/h3>\n\n\n\n<p>Let&#8217;s take an example that we want to sort worker\u2019s arrays based on age property which is number.<\/p>\n\n\n\n<p>We will use the arrow function which has a much smaller syntax:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Sorting the 'workers' array based on the 'age' property in ascending order\n\nlet sortedByAge = workers.sort((x, y) =&gt; x.age - y.age);<\/pre><\/div>\n\n\n\n<p>Here sortedByAge is storing the sorted array. (x, y) => x.age &#8211; y.age)\u00a0 this is an arrow function behaving as a compareFunction.<\/p>\n\n\n\n<p>It returns positive, negative, or zero based on the age values of both objects. If x.age-y.age is negative it means \u2018x\u2019 is smaller and will come before \u2018y\u2019 in sorted order. Similarly, if this is positive it means \u2018x\u2019 is bigger than \u2018y\u2019 and will come after \u2018y\u2019. If the value of both is the same then it will return 0.<\/p>\n\n\n\n<p>Let&#8217;s see the results:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Logging the sorted workers array to the console\n\nconsole.log(sortedByAge);  <\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>&#91;\n  {\n    firstName: 'Advin',\n    lastName: 'Mark',\n    age: 21,\n    joinDate: 'December 15, 2023'\n  },\n  {\n    firstName: 'Marry',\n    lastName: 'Con',\n    age: 23,\n    joinDate: 'January 20, 2023'\n  },\n  {\n    firstName: 'Lily',\n    lastName: 'Potter',\n    age: 30,\n    joinDate: 'June 25, 2023'\n  },\n  {\n    firstName: 'Harry',\n    lastName: 'Potter',\n    age: 32,\n    joinDate: 'February 25, 2023'\n  }\n]\n<\/code><\/pre>\n\n\n\n<p>As we can see we can sort workers based on the numeric value \u2018age\u2019. If we want to sort it in decreasing order we can simply reverse the logic.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Sorting the 'workers'' array based on the 'age' property in descending order\n\nlet sortedByAge = workers.sort((x, y) =&gt; y.age - x.age);<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2) Sorting By String Values<\/strong><\/h3>\n\n\n\n<p>Let&#8217;s take the case that we want to sort workers based on firstName in ascending order. <strong>We know that while dealing with a simple array with a primitive value like a string we can easily sort it using an array.sort() method without the need for any compareFunction.<\/strong><\/p>\n\n\n\n<p>But we need to know that this straightforward approach is not applicable when the data we want to sort is nested within a property of objects within the array, rather than the array itself. So we have to manually specify where the string data is located.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Using the sort() method with a custom comparison function\n\/\/ Sorting workers by their first names in ascending order\n\nsortedByFirstName = workers.sort((x, y) =&gt; {\n    \/\/ Convert first names to lowercase for case-insensitive sorting\n    let fx = x.firstName.toLowerCase(), fy = y.firstName.toLowerCase();\n\n    \/\/ Return a negative value if x should be placed before y\n    if (fx &lt; fy) {\n        return -1;\n    }\n\n    \/\/ Return a positive value if x should be placed after y\n    if (fx &gt; fy) {\n        return 1;\n    }\n\n    \/\/ Return 0 if x and y have the same order\n    return 0;\n});\n\n\/\/ 'sortedByFirstName' now contains the worker's array sorted by first names<\/pre><\/div>\n\n\n\n<p>Here first of all we converted our names into lowercase to ensure case-in-sensitive sorting. Then we returned -1,1 or 0 based on comparisons. More appropriately we returned -1 if \u2018x\u2019 should be placed before \u2018y\u2019,1 if \u2018x\u2019 should be placed after \u2018y\u2019, and 0 if no change.<\/p>\n\n\n\n<p>Let&#8217;s see the results.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Logging the sorted workers array to the console\n\nconsole.log(sortedByFirstName);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>&#91;\n  {\n    firstName: 'Advin',\n    lastName: 'Mark',\n    age: 21,\n    joinDate: 'December 15, 2023'\n  },\n  {\n    firstName: 'Harry',\n    lastName: 'Potter',\n    age: 32,\n    joinDate: 'February 25, 2023'\n  },\n  {\n    firstName: 'Lily',\n    lastName: 'Potter',\n    age: 30,\n    joinDate: 'June 25, 2023'\n  },\n  {\n    firstName: 'Marry',\n    lastName: 'Con',\n    age: 23,\n    joinDate: 'January 20, 2023'\n  }\n]\n<\/code><\/pre>\n\n\n\n<p>So we have sorted workers based on firstNames in ascending order.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3) Sorting By Dates<\/strong><\/h3>\n\n\n\n<p>We have our dates in the form of strings, so first of all we need to convert them into Date objects. After that, the method is similar to comparing two numbers. We will take joinDate strings from each worker, convert them into Date objects, and then use these Date objects for comparison in the sorting process. Let&#8217;s see its code:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Sorting workers based on their joinDate property\n\n\/\/ Using the sort() method with a custom comparison function\nsortedByDate = workers.sort((x, y) =&gt; {\n    \/\/ Convert joinDate strings to Date objects\n    let dateX = new Date(x.joinDate);\n    let dateY = new Date(y.joinDate);\n\n    \/\/ Compare Date objects to achieve ascending sorting\n    return dateX - dateY;\n});\n\n\/\/ 'workers' array is now sorted based on joinDate in ascending order<\/pre><\/div>\n\n\n\n<p>Here let dateX = new Date(x.joinDate) and let dateY = new Date(y.joinDate); convert the joinDate strings into Date objects.<\/p>\n\n\n\n<p>Let&#8217;s see the results:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Logging the sorted workers array to the console\n\nconsole.log(sortedByDate);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>&#91;\n  {\n    firstName: 'Marry',\n    lastName: 'Con',\n    age: 23,\n    joinDate: 'January 20, 2023'\n  },\n  {\n    firstName: 'Harry',\n    lastName: 'Potter',\n    age: 32,\n    joinDate: 'February 25, 2023'\n  },\n  {\n    firstName: 'Lily',\n    lastName: 'Potter',\n    age: 30,\n    joinDate: 'June 25, 2023'\n  },\n  {\n    firstName: 'Advin',\n    lastName: 'Mark',\n    age: 21,\n    joinDate: 'December 15, 2023'\n  }\n]\n<\/code><\/pre>\n\n\n\n<p>We have sorted our objects successfully based on dates.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>4) Sort Using Multiple Criteria<\/strong><\/h3>\n\n\n\n<p>We can also sort by taking into consideration multiple properties. For example, we can sort based on last name in ascending order, but what if we have the same last name of two workers? Then we can consider the first name of the workers. By this, we are considering multiple properties of workers.<\/p>\n\n\n\n<p>Here also we will first of all convert into lowercase for case in-sensitive sort. After that we will compare last names and return 1 or -1; if last names are the same, we will move to first names with similar logic. See an example below:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">sortedByName = workers.sort((x, y) =&gt; {\n  \/\/ Convert last names and first names to lowercase for case-insensitive sorting\n  let lastNameX = x.lastName.toLowerCase();\n  let lastNameY = y.lastName.toLowerCase();\n  let firstNameX = x.firstName.toLowerCase();\n  let firstNameY = y.firstName.toLowerCase();\n\n  \/\/ Compare last names\n  if (lastNameX &lt; lastNameY) {\n    return -1;\n  }\n  if (lastNameX &gt; lastNameY) {\n    return 1;\n  }\n\n  \/\/ If last names are equal, compare first names\n  if (firstNameX &lt; firstNameY) {\n    return -1;\n  }\n  if (firstNameX &gt; firstNameY) {\n    return 1;\n  }\n\n  \/\/ If both last names and first names are equal, return 0\n  return 0;\n});<\/pre><\/div>\n\n\n\n<p>Let&#8217;s see the results:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Logging the sorted workers array to the console\n\nconsole.log(sortedByName);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code> &#91;\n  {\n    firstName: 'Marry',\n    lastName: 'Con',\n    age: 23,\n    joinDate: 'January 20, 2023'\n  },\n  {\n    firstName: 'Advin',\n    lastName: 'Mark',\n    age: 21,\n    joinDate: 'December 15, 2023'\n  },\n  {\n    firstName: 'Harry',\n    lastName: 'Potter',\n    age: 32,\n    joinDate: 'February 25, 2023'\n  },\n  {\n    firstName: 'Lily',\n    lastName: 'Potter',\n    age: 30,\n    joinDate: 'June 25, 2023'\n  }\n]\n<\/code><\/pre>\n\n\n\n<p>We can see that we have sorted based on lastName first and in the case where both the lastName were the same we have sorted considering the firstName.<\/p>\n\n\n\n<p>Now you can move on to <a href=\"https:\/\/favtutor.com\/articles\/empty-array-javascript\/\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/articles\/empty-array-javascript\/\">empty an array in JavaScript<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>Sorting an array of objects is a fundamental operation for any developer. By utilizing the sort() method and providing a custom comparison function we were able to arrange the array of objects based on specific needs. We discussed different ways of sorting like by numeric values, strings, and dates.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sorting means putting things in order. It is needed very often in javascript programs. In this article, we will learn how to sort an array of objects in Javascript based on specific criteria, such as numeric values, strings, or other custom properties. Let\u2019s explore this topic which will help us to effortlessly order data, contributing [&hellip;]<\/p>\n","protected":false},"author":13,"featured_media":1393,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11],"class_list":["post-1386","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1386","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1386"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1386\/revisions"}],"predecessor-version":[{"id":1399,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1386\/revisions\/1399"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1393"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1386"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1386"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1386"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}