How to compare two arrays for Matches in JavaScript?

23-May-2023

.

Admin

How to compare two arrays for Matches in JavaScript?

Now, let's see example of How to compare two arrays in JavaScript. We will look at example of Comparison of Two arrays Using JavaScript. I explained simply about How can I find matching values in two arrays. if you have question about JavaScript match values in two arrays then I will give simple example with solution. Here, Creating a basic example of Compare Two Arrays in JavaScript.

There are several ways to compare two arrays for matches in JavaScript. Here are some examples:

Example 1: Using the includes() method


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to compare two arrays for Matches in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr1 = [1, 2, 3];

const arr2 = [2, 4, 6];

arr1.forEach(num => {

if (arr2.includes(num)) {

console.log(`${num} is a match!`);

}

});

</script>

</html>

Example 2: Using the filter() method

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to compare two arrays for Matches in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr1 = [1, 2, 3];

const arr2 = [2, 4, 6];

const matches = arr1.filter(num => arr2.includes(num));

console.log(matches); // Output: [2]

</script>

</html>

Example 3: Using the reduce() method

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to compare two arrays for Matches in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr1 = [1, 2, 3];

const arr2 = [2, 4, 6];

const matches = arr1.reduce((acc, num) => {

if (arr2.includes(num)) {

acc.push(num);

}

return acc;

}, []);

console.log(matches); // Output: [2]

</script>

</html>

#JavaScript