How to usefor Loop and indexOf() Method in Javascript
To find the difference between two arrays in JavaScript, you can iterate over one array using a for loop and check if each element exists in the other array using the indexOf() method. If an element is not found, it is added to the result array.
Syntax:
function arrayDiff(a, b) {
let difference = [];
for (let i = 0; i < a.length; i++) {
if (b.indexOf(a[i]) === -1) {
difference.push(a[i]);
}
}
return difference;
};
Example: In this example, we define a function called arrayDifference that takes in two arrays as parameters. We initialize an empty array called difference to store the elements that are present in arr1 but not in arr2. We then use a for loop to iterate over each element in arr1. For each element, we use the indexOf() method to check if it exists in arr2. If the indexOf() returns -1, indicating that the element is not found in arr2, we push it into the difference array.
function arrayDifference(arr1, arr2) {
const difference = [];
for (let i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) === -1) {
difference.push(arr1[i]);
}
}
return difference;
}
const array1 = [1, 2, 3, 4, 5, 0];
const array2 = [3, 4, 5, 6, 7, 9];
const difference = arrayDifference(array1, array2);
console.log(difference);
Output
[ 1, 2, 0 ]
How to Get the Difference Between Two Arrays in JavaScript ?
The problem is to find the difference between two arrays in JavaScript. The objective is to identify the elements that exist in one array but not in the other and return them as a new array.
These are the approaches to achieve differences between two arrays are:
Table of Content
- Approach 1: Using the filter() and includes() methods
- Approach 2: Using for Loop and indexOf() Method
- Approach 3: Using Set and filter() Method
- Approach 4: Using reduce() and includes() Methods
- Approach 6: Using Array.filter() and Array.every() Methods