Write a JavaScript Program to Compare Elements of Two Arrays

In JavaScript, comparing elements of two arrays is a common task that you may encounter when working on projects involving data manipulation.

In this tutorial, we will cover how to compare elements of two arrays in JavaScript.

To begin with, let’s create two arrays with some elements in them:

const array1 = [1, 2, 3, 4, 5];
const array2 = [1, 3, 5, 7, 9];

Now, we want to compare the elements of these two arrays to see which ones are present in both arrays. We can do this using a for loop and the includes() method.

for(let i = 0; i < array1.length; i++) {
  if(array2.includes(array1[i])) {
    console.log(array1[i] + " is present in both arrays");
  }
}

In this code, we loop through each element of the first array using a for loop.

For each element, we check if it is present in the second array using the includes() method.

If it is present, we log a message to the console indicating that the element is present in both arrays.

We can also use the filter() method to create a new array containing the elements that are present in both arrays.

const commonElements = array1.filter(element => array2.includes(element));
console.log(commonElements);

In this code, we use the filter() method to create a new array called commonElements.

The filter() method loops through each element of the first array and returns a new array containing only the elements that are present in both arrays.

Finally, we log the commonElements array to the console to see which elements are present in both arrays.

In conclusion, comparing elements of two arrays in JavaScript is a simple task that can be accomplished using a for loop and the includes() method or the filter() method.