How to Get Common or Same Elements From Two Arrays in Javascript Full Project For Beginners

 

Welcome folks today in this blog post we will be getting common or same elements from two arrays in javascript. All the full source code of the application is given below.

 

 

 

Get Started

 

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

See also  How to Convert HTML5 Button to Anchor Link Tag and Redirect User to Different Page Using onclick Attribute Using Javascript Full Project For Beginners

 

 

// Function to return commonElements
function getCommon(arr1, arr2) {
  var common = [];                   // Array to contain common elements

  for(var i=0 ; i<arr1.length ; ++i) {
    for(var j=0 ; j<arr2.length ; ++j) {
      if(arr1[i] == arr2[j]) {       // If element is in both the arrays
        common.push(arr1[i]);        // Push to common array
      }
    }
  }
  
  return common;                     // Return the common elements
}

var arr1 = [45, 99, 55, 223, 17, 93, 23];
var arr2 = [45, 18, 93, 7, 23, 1, 223, 5];

// Get common elements of arr1, arr2
var commonElements = getCommon(arr1, arr2); // [45, 223, 93, 23]

Leave a Reply