{"id":1706,"date":"2024-02-17T13:00:00","date_gmt":"2024-02-17T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1706"},"modified":"2024-02-20T06:12:03","modified_gmt":"2024-02-20T06:12:03","slug":"compare-two-arrays-javascript","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/compare-two-arrays-javascript\/","title":{"rendered":"Compare Two Arrays in JavaScript (5 Methods)"},"content":{"rendered":"\n<p>When working with JavaScript, we often come across situations where we need to compare two arrays to check if they are equal or not. In this article, we will cover various methods to compare two arrays in JavaScript using conversion to strings, looping through array elements, and using external libraries.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>5 Ways to Compare Two Arrays in JavaScript<\/strong><\/h2>\n\n\n\n<p><strong>We can compare any two values in JavaScript by \u201c==\u201d and \u201c===\u201d, but this is not applicable here because the datatype of an array is an object, and when comparing objects the equality operators check for reference equality rather than value equality.<\/strong><\/p>\n\n\n\n<p>Let&#8217;s explore methods to compare two arrays. It&#8217;s important to note that each method may have some drawbacks, therefore we have to choose the best method according to our use case.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1) JSON.stringify()<\/strong><\/h3>\n\n\n\n<p><strong>The simplest way to compare two arrays in JavaScript is by converting an array into a JSON string, making them ready for comparison directly.<\/strong>\u00a0<\/p>\n\n\n\n<p>For 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;}\">\/\/ Declare three arrays\nlet arr1 = [1,2,4,5];\nlet arr2 = [1,2,3,4];\nlet arr3 = [1,2,4,5];\n\n\/\/ Comparing using stringify method\n\nconsole.log(JSON.stringify(arr1) === JSON.stringify(arr2));\n\nconsole.log(JSON.stringify(arr1) === JSON.stringify(arr3));<\/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 has-link-color wp-elements-4e0cf8388a5a536bc39d9331d15d340e\" style=\"background-color:#fedcba\"><code>false\ntrue\n<\/code><\/pre>\n\n\n\n<p>We can successfully compare two arrays with this method. However, some points to keep in mind are:<\/p>\n\n\n\n<p>As this method converts JavaScript objects(including arrays) to JSON-formatted strings, therefore null and undefined both are represented as null. We should avoid this method if we want to treat null and undefined distinctly.<\/p>\n\n\n\n<p>This method works well for basic data types like strings, numbers, and objects. However, it does not support custom objects with methods like Map, Set, or arrays that contain functions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2) Using .toString()<\/strong><\/h3>\n\n\n\n<p>The .toString() method converts any data types, including objects to a string representation which can then be compared directly.<\/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;}\">\/\/ Declare three arrays\nlet arr1 = [1,2,4,5];\nlet arr2 = [1,2,3,4];\nlet arr3 = [1,2,4,5];\n\n\/\/ Comparing using .toString method\n\nconsole.log(arr1.toString() === arr2.toString());\n\nconsole.log(arr1.toString() === arr3.toString());<\/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 has-link-color wp-elements-4e0cf8388a5a536bc39d9331d15d340e\" style=\"background-color:#fedcba\"><code>false\ntrue\n<\/code><\/pre>\n\n\n\n<p>However JSON.stringify() is preferred over .toString() because of following reasons:<\/p>\n\n\n\n<p>`JSON.stringify` preserves the structure of the array. It serializes the array into a string without altering its original shape. This is important when dealing with nested arrays or arrays of objects.<\/p>\n\n\n\n<p>When an array contains nested arrays or objects, `JSON.stringify` recursively serializes, whereas .toString() simply converts the array to a comma-separated string, which leads to loss of hierarchical information. For 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;}\">\/\/ Original array with different data types and nested structures\nlet array = [1, [2, 3], { key: 'value' }];\n\n\/\/ using .toString() method on the array\nconsole.log(array.toString());\n\n\/\/ using JSON.stringify() method on the array\nconsole.log(JSON.stringify(array));<\/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 has-link-color wp-elements-d14f75eb9b53fda79313542d173a5879\" style=\"background-color:#fedcba\"><code>\"1,2,3,&#91;object Object]\"\n\"&#91;1,&#91;2,3],{\"key\":\"value\"}]\"\n<\/code><\/pre>\n\n\n\n<p>Therefore `JSON.stringify` provides a more accurate and complete representation of the array, including nested arrays and objects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3) Using every()<\/strong><\/h3>\n\n\n\n<p>This is an example of looping over the array, we can compare each element of an array to the corresponding element in the other array. In the every() method, a callback function is executed for each element in an array, which receives the current element, its index, and the array as parameters.<\/p>\n\n\n\n<p>We will first check the length of both arrays because if the length is not the same, then no need to check the whole array. 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;}\">\/\/ Function to compare two arrays element-wise\nconst comparison = (arrayA, arrayB) =&gt; {\n  \/\/ Check if the lengths of the arrays are equal\n  \/\/ and if every corresponding value in the arrays is identical\n  return (\n    arrayA.length === arrayB.length &amp;&amp;\n    arrayA.every((value, index) =&gt; value === arrayB[index])\n  );\n};\n\n\/\/ Example arrays for testing the comparison function\nlet array1 = [1, 2, 3, null];\nlet array2 = [2, 2, 3, 4];\nlet array3 = [1, 2, 3, undefined];\n\n\/\/ Testing the comparison function with example arrays\nconsole.log(comparison(array1, array2));\nconsole.log(comparison(array1, array3));<\/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 has-link-color wp-elements-5e209d977ddd41bcfe7d3fc3ee250a64\" style=\"background-color:#fedcba\"><code>false\nfalse\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>4) Using a for Loop<\/strong><\/h3>\n\n\n\n<p>This method involves manually iterating over each element of the arrays and comparing them one by one. It uses a for loop in combination with if statements. This is an easy method for beginners and provides more control over the comparison process.<\/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;}\">function comparison(array1, array2) {\n  \/\/ Check if the arrays have the same length\n  if (array1.length !== array2.length) {\n    return false;\n  }\n\n  \/\/ Iterate through the elements of the arrays\n  for (let i = 0; i &lt; array1.length; i++) {\n    \/\/ Compare the current elements\n    if (array1[i] !== array2[i]) {\n      return false;\n    }\n  }\n\n  \/\/ If the loop completes without returning false, the arrays are equal\n  return true;\n}\n\n\/\/ Example arrays for testing the comparison function\nlet Array1 = [1, 2, 3, null];\nlet Array2 = [1, 2, 3, 4];\nlet Array3 = [1, 2, 3, Undefined];\nlet Array4 = [1, 2, 3, 4];\n\n\n\/\/ Testing the comparison function with example arrays\nconsole.log(comparison(Array1, Array2));\nconsole.log(comparison(Array1, Array3));\nconsole.log(comparison(Array2, Array4));<\/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 has-link-color wp-elements-97a05c7a91265ff49c5148fd1bf06139\" style=\"background-color:#fedcba\"><code>false\nfalse\ntrue\n<\/code><\/pre>\n\n\n\n<p>Here after comparing lengths, we compared each element at the corresponding index. If any pair of elements is not equal, the function returns false. If all the elements pass the comparison, true is returned.<\/p>\n\n\n\n<p>But we have to keep in mind for comparing more complex scenarios, especially involving nested arrays or objects, we may need to implement additional custom logic.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>5) Using Lodash _.isEqual()<\/strong><\/h3>\n\n\n\n<p>If you prefer using external libraries, Lodash provides a convenient method known as isEqual() to compare two arrays. We first need to import the _.isEqual() library.<\/p>\n\n\n\n<p><strong>The Lodash _.isEqual() method performs a deep comparison, which is beneficial when we are comparing arrays in a more complex scenario such as when the arrays contain objects or nested arrays.<\/strong><\/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;}\">\/\/ Importing isEqual method from lodash\nconst  _ = require('lodash');\n\n\/\/ Example arrays\nconst Array1 = [1, 2, 3];\nconst Array2 = [1, 2, 3];\nconst array3 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];\nconst array4 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Charlie' }];\n\n\/\/Checking for equal values\nconsole.log(_.isEqual(Array1,Array2));\nconsole.log(_.isEqual(Array3,Array4));<\/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 has-link-color wp-elements-f7422b2a7ee8de766917e7b716657a10\" style=\"background-color:#fedcba\"><code>true\nfalse\n<\/code><\/pre>\n\n\n\n<p>This method can be a convenient and reliable way to compare arrays, especially in cases when we have complex data structures.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>We have successfully covered various methods to compare two arrays in JavaScript, with their advantages and limitations. Therefore which method to opt for will depend on the use case. Now you can learn to <a href=\"https:\/\/favtutor.com\/articles\/sort-an-array-of-objects-in-javascript\/\">Sort an Array of Objects in JavaScript.<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand how to compare two arrays in JavaScript, along with converting to strings, looping and using external libraries.<\/p>\n","protected":false},"author":13,"featured_media":1708,"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,13],"class_list":["post-1706","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript","tag-javascript-array"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1706","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=1706"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1706\/revisions"}],"predecessor-version":[{"id":2180,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1706\/revisions\/2180"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1708"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1706"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1706"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1706"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}