Grambam
Grambam

Reputation: 554

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

Upvotes: 0

Views: 110

Answers (3)

Angel Marin
Angel Marin

Reputation: 61

A shorter script:

function differenceWithDuplicates(a, b) {
    while(b.length) a.splice(a.indexOf(b[0]), +a.includes(b.shift()));
    return a;
}
console.log(differenceWithDuplicates([1, 1, 7, 6],[1, 7]));

Or just make the while, without call it inside a function.

Upvotes: 2

Steve Vaughan
Steve Vaughan

Reputation: 2189

You could do something along the lines of:

const diff = (array1, array2) => {

    const _array2 = Array.from(array2);
    const difference = [];

    array1.forEach((array1Item) => {
        const matchedIndex = _array2.findIndex(array2Item => array2Item === array1Item);
        if (matchedIndex > -1) {
            // Remove from second array
            _array2.splice(matchedIndex, 1);
        } else {
            // No match found, add to difference array
            difference.push(array1Item);
        }
    });

    // Return the remaining items in _array2 and difference
    return [ ..._array2, ...difference ];
}

By copying the second array, you can remove any matches from it. And by combining that with matching array1 > array2, you get differences in both directions, including duplicates.

Working fiddle: https://jsfiddle.net/3v34tjnq/

Upvotes: 1

Andrew
Andrew

Reputation: 7545

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]))

Upvotes: 2

Related Questions