This algorithm problem asks to compare two arrays, and return a new array containing the difference of the two arrays. Here is how to solve the problem:
Step 1. Setting up the answer:
function difArray(array1, array2) {
}
difArray([1, 2, 3, 5], [1, 2, 3, 4, 5])
Here, we have two arrays. We want to compare them, and return a new array that would contain the difference. In this case, it would be the number 4.
Step 2. Loop through both arrays and push unique values to empty array.
const union = []
for (let i = 0; i < array1.length; i++) {
if (!union.includes(array1[i])) {
union.push(array1[i])
}
}
for (let i = 0; i < array2.length; i++) {
if (!union.includes(array2[i])) {
union.push(array2[i]);
}
}
}
Step 3. Loop through union array and compare the elements, adding the different elements to a new array
function difArray(array1, array2) {
const union = []
for (let i = 0; i < array1.length; i++) {
if (!union.includes(array1[i])) {
union.push(array1[i])
}
}
for (let i = 0; i < array2.length; i++) {
if (!union.includes(array2[i])) {
union.push(array2[i]);
}
}
const difference = []
for (let i = 0; i < union.length; i++){
const current = union[i];
if (array1.includes(current) && !array2.includes(current)){
difference.push(current)
} else if (array2.includes(current) && !array1.includes(current)){
difference.push(current)
}
}
return difference
}
And you're done!
Top comments (1)
You can do it in a single loop if you use separate indices: