Search code examples
javascriptarrayslodash

Compare two arrays and create a new array with the differences, accounting for duplicates


Lets say I have two arrays containing numbers..

[1,1,7,6], [1,7]

I need to create a new array out of the numbers that do not appear in the second array, but also account for there being two 1s.

I have tried using lodash's _.difference([1,1,7,6],[1,7])

as well as some other plain Javascript functions, but they do not account for the there being two 1s, so I just end up with [6]

My desired outcome would be [1,6]

Order does not matter


Solution

  • Iterate over the first array. For each element in the first array, search the second. If it exists, insert null into that index. If it doesn't exist, then push it to a new array with your differences

    const difference = (arr1, arr2) => {
        const differenceArr = []
        for (let i = 0; i < arr1.length; i++) {
            const matchingIdx = arr2.indexOf(arr1[i]);
            if (matchingIdx !== -1) {
                arr2[matchingIdx] = null
            } else {
                differenceArr.push(arr1[i])
            }
        }
        return differenceArr
    }
    
    console.log(difference([1, 1, 7, 7, 6],[1, 1, 7]))