JavaScript – Compare Arrays – Get Matching Unique Values from two Arrays

In this guide, we will discuss how to compare and get matching values like strings or numbers from two Arrays? The result will be the set of values that are available in both arrays.

While working in Javascript may need to compare two arrays to find intersection values that are matching and fetch out the matching values. We are going to discuss a few approaches using which you can easily and quickly compare Arrays to get a matching array set.

The methods will be for both the latest ES6 TypeSctipt which we use in angular and other modern Javascript applications, and also we will discuss methods for older browsers.

How to find matching values in two arrays in JavaScript?

For testing our results, we will have the following two sets of arrays:

Test Arrays

Number Arrays:

let numArr1 = [ 53, 8, 14, 7, 96, 23, 5, 23, 85, 8, 99, 13, 304];
let numArr2 = [ 3, 99, 45, 12, 78, 45, 36, 23, 97, 111, 5];

String Arrays:

let strArr1 = [ 'aaa', 'bbb', 'ccc', 'aa', 'aaa', 'c', 'bbb']; 
let strArr2 = [ 'bab', 'bb', 'ddd', 'aa', 'aa', 'ccc', 'bbb'];

 

So, we have arrays available to find matching values or intersection values that are similar in both arrays.

 

1# Method: For Moder Browsers – ES6

// Number Array Comparison
let numArr1 = [ 53, 8, 14, 12, 1, 5, 5, 7, 96, 23, 5, 23, 85, 8, 99, 13, 304]; 
let numArr2 = [ 3, 99, 45, 12, 5, 5, 78, 45, 36, 23, 97, 111, 5];

const filteredNumArray = numArr1.filter(value => numArr2.includes(value)).filter((value, index, self) => self.indexOf(value) === index);
console.log(filteredNumArray); // [12, 5, 23, 99]

// String Array Comparison
let strArr1 = [ 'aaa', 'bbb', 'ccc', 'aa', 'aaa', 'c', 'bbb']; 
let strArr2 = [ 'bab', 'bb', 'ddd', 'aa', 'aa', 'ccc', 'bbb'];

const filteredStrArray = strArr1.filter(value => strArr2.includes(value)).filter((value, index, self) => self.indexOf(value) === index);
console.log(filteredStrArray); // ["bbb", "ccc", "aa"]

 

In this ES6 or Typescript method for modern browsers, we used filter() & includes()

Array1 is filtered by checking if each value exists in Array2 by returning the boolean from includes() method. At this point, the value returned will be [12, 5, 5, 23, 5, 23, 99]

If you see up to this point we have filtered the matching values, but duplicate values are there.

To resolve or get unique value from the filtered array, we added the filter() method again and using the indexOf() to compare values from self and fetch unique values.

Moreover, you can also wrap it in a function as shown below:

function retunIntersaction(arr1, arr1){
    return arr1.filter(value => arr1.includes(value)).filter((value, index, self) => self.indexOf(value) === index);
}
console.log(retunIntersaction(strArr1, strArr2)); // ["bbb", "ccc", "aa"]

 

Note: Old Browsers (<ie9),do not support the native methods filter and includes .For those you can go for the next method.

 

2# Method: Supported for Old Browsers

function compareArray(arr1, arr2) {
  var arr = [];  // Array to get mached values
  for(var i=0 ; i<arr1.length ; ++i) {
    for(var j=0 ; j<arr2.length ; ++j) {
      if(arr1[i] == arr2[j]) {    // If value insects found in both arrays
        arr.push(arr1[i]);        // Push to arr array
      }
    }
  }
  // Fetch only unique values
  var uniqueArr = [];
    for (var i=0, l=arr.length; i<l; i++)
        if (uniqueArr.indexOf(arr[i]) === -1 && arr[i] !== '')
        uniqueArr.push(arr[i]);
  return uniqueArr;
}
 
console.log(compareArray(numArr1, numArr2)); // [12, 5, 23, 99]
console.log(compareArray(strArr1, strArr2)); // ["bbb", "ccc", "aa"]

 

Above, we have used nested for loops to push the matching values in an array named arr. After getting all the matching values, we have added another for loop to get only unique values out of the matched values.

The indexOf method we used here is supported in most of the available browser versions including IE legacy.

Leave a Reply

Your email address will not be published. Required fields are marked *