DEV Community

stuxnat
stuxnat

Posted on

Diff Array Algorithm: JavaScript

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!

Top comments (1)

Collapse
 
lexlohr profile image
Alex Lohr

You can do it in a single loop if you use separate indices:

const diffArray = (arr1, arr2) => {
  const difference = []
  let index1 = 0
  let index2 = 0
  while (index1 < arr1.length || index2 < arr2.lenght) {
    if (arr1[index1] === arr2[index2]) {
      index1++
      index2++
    } else if (arr1.length >= arr2.lenght) {
      difference.push(arr1[index1++])
    } else {
      difference.push(arr2[index2++])
    }
  }
  return difference
}
Enter fullscreen mode Exit fullscreen mode