How to compare two arrays when the key is a string - JavaScript



Comparing two arrays in JavaScript can be tricky when the key is a string. String comparisons are case-sensitive and require special handling to ensure proper results.

Fortunately, there are several methods you can use to compare two arrays when the key is a string in JavaScript. In this article, we’ll discuss how to effectively compare two arrays with strings as keys using various approaches such as map(), Include(). Intersection() and Arrayfilter().

Strings in JavaScript are used to store and modify text. A string in JavaScript is defined as zero or more characters enclosed in quotations. Data that can be represented as text can be stored in strings. Using the String() constructor, strings can be created as primitives, from string literals, or as objects.

Using map() in JavaScript

The Map() is a built-in JavaScript method that creates a new array with the results of calling a provided function on every element in an array. It can be used to iterate through an array, modify each item, and return the modified items as a new array. For empty items, the function is not run by map(). The initial array is unaffected by map().

Syntax

Following is the syntax for map()

array.map(function(currentValue, index, arr), thisValue)

The include() in JavaScript

In JavaScript, the include() method is used to determine if a string contains another substring. The result is returned as either true or false.

Syntax

Following is the syntax for include()

string.includes(searchvalue, start)

Example

In the following example we are running a script to compare two arrays by using map() and include().

<!DOCTYPE html>
<html>
<body>
   <script>
      const arr1 = [
         { "car": "Bmw"},
         { "car": "BENZ"},
         { "car": "Audi"},
         { "car": "Jaguar"}
      ];
      const arr2 = [
         { "car": "Audi"},
         { "car": "City"},
         { "car": "Jaguar"},
         { "car": "Verna" }
      ];
      const extractValue = ({ 'car': car }) => car;
      const duplicateValues = arr1
      .map(extractValue)
      .filter(x => arr2
         .map(extractValue)
         .includes(x)
      );
      document.write(JSON.stringify(duplicateValues));
   </script>
</body>
</html>

When the script gets executed, it will generate an output consisting of an array printed on the web-browser. This is caused by an event that gets triggered that makes the two arrays compare each other and provide the new array.

Example

Consider the following example, where we are using the intersection; in this case, it first looks for the longest array and gets filtered, so the shortest array is used as an array to search within.

<!DOCTYPE html>
<html>
<body>
   <script>
      const first = [
         { "bike": "Rx100"},
         { "bike": "R15"},
         { "bike": "Revolt"},
         { "bike": "Duke"}
      ]
      const second = [
         { "bike": "Deluxe"},
         { "bike": "Rx100"},
         { "bike": "Splendor"}
      ]
      const intersection = (longer, shorter, key) => {
         let tmp;
         if (shorter.length > longer.length) {
            tmp = shorter, shorter = longer, longer = tmp;
         }
         const vals = shorter.map(entry => entry[key]);
         return longer.filter(entry => vals.find(v => v ===entry[key]));
      }
      const key = 'bike';
      const third = intersection(first, second, key);
      document.write(JSON.stringify(third.flatMap(Object.values)));
   </script>
</body>
</html>

On running the above script, the output window will pop up, displaying the array on the web-browser, which was caused by the event that gets triggered on running the script.

Example

Let’s look at the following example, where we are using Array.filter to run through the first array and return the value that was found in the second array.

<!DOCTYPE html>
<html>
<body>
   <script>
      const array1 = [
         { "movie": "Balu"},
         { "movie": "Gabbar"},
         { "movie": "Bheem"},
      ];
      const array2 = [
         { "movie": "Jalsa"},
         { "movie": "Balu"},
      ];
      const array2String = JSON.stringify(array2);
      const duplicates = array1.filter(x =>array2String.includes(JSON.stringify(x)));
      document.write(JSON.stringify(duplicates))
   </script>
</body>
</html>

When the script gets executed, the event gets triggered, which compares the two arrays used in the script and returns the values found between the two arrays on the webbrowser.


Advertisements