Home > Back-end >  How do I get the difference between two FIFO array states?
How do I get the difference between two FIFO array states?

Time:11-18

I have two arrays that represent a fifo-like state, an old state and a new state. I need a function that finds the newly added items by comparing the new array with the old one. Below 3 examples of two arrays where 1 has items added to the front of it compared to the other:

// Input 1
const arr1 = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ];
const arr2 = [ 'a', 'b', 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]; // added 'a' and 'b' in front

// Input 2
const arr3 = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ];
const arr4 = [ 'q', 'r', 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]; // added 'q' and 'r' in front

// Input 3
const arr5 = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ];
const arr6 = [ 'a', 'b', 'q', 'a', 'b', 'c', 'd', 'e', 'f' ]; // added 'a' 'b' and 'q' in front

Note that the amount of newly added items is removed from the back of the array. Here the desired functionality getItemsAdded(arr1, arr2) function:

// Desired output for 'diff()' function
console.log(getItemsAdded(arr1, arr2)); // [ 'a', 'b' ]
console.log(getItemsAdded(arr3, arr4)); // [ 'q', 'r' ]
console.log(getItemsAdded(arr3, arr4)); // [ 'a', 'b', 'q' ]

It feels like such a simple problem, but I cant get my head around it.. I couldn't solve it with solutions provided here How to get the difference between two arrays in JavaScript?, since its a different problem.

CodePudding user response:

Code can tell more words, Then my silly explanation...

// Input 1
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
const arr2 = ['a', 'b', 'a', 'b', 'c', 'd', 'e', 'f', 'g']; // added 'a' and 'b' in front
// Input 2
const arr3 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
const arr4 = ['q', 'r', 'a', 'b', 'c', 'd', 'e', 'f', 'g']; // added 'q' and 'r' in front
// Input 3
const arr5 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
const arr6 = ['a', 'b', 'q', 'a', 'b', 'c', 'd', 'e', 'f']; // added 'a' 'b' and 'q' in front
// Desired output for 'diff()' function
console.log(getItemsAdded(arr1, arr2)); // [ 'a', 'b' ]
console.log(getItemsAdded(arr3, arr4)); // [ 'q', 'r' ]
console.log(getItemsAdded(arr5, arr6)); // [ 'a', 'b', 'q' ]

function cmp(arr1, arr2) {
    for (let i = 0; i < arr2.length; i  )
        if (arr2[i] != arr1[i])
            return i == 0 ? 1 : i
}
function getItemsAdded(arr1, arr2) {
    let q = [];
    while (arr2.length) {
        let i = cmp(arr1, arr2);
        if (i === undefined) return q;
        q.push(...arr2.splice(0, i))
    }
    return q;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related