Diff Array Algorithm: JavaScript

stuxnat - Jan 9 '22 - - Dev Community

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])
Enter fullscreen mode Exit fullscreen mode

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]);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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 
}
Enter fullscreen mode Exit fullscreen mode

And you're done!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player