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:
JavaScript
x
13
13
1
// Input 1
2
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
3
const arr2 = ['a', 'b', 'a', 'b', 'c', 'd', 'e', 'f', 'g']; // added 'a' and 'b' in front
4
// Input 2
5
const arr3 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
6
const arr4 = ['q', 'r', 'a', 'b', 'c', 'd', 'e', 'f', 'g']; // added 'q' and 'r' in front
7
// Input 3
8
const arr5 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
9
const arr6 = ['a', 'b', 'q', 'a', 'b', 'c', 'd', 'e', 'f']; // added 'a' 'b' and 'q' in front
10
// New Input 4
11
const arr7 = ['a', 'b', 'a', 'b', 'c', 'd', 'e', 'f', 'g'];
12
const arr8 = ['a', 'b', 'a', 'b', 'a', 'b', 'c', 'd', 'e']; // added 'a' and 'b' in front
13
Note that the amount of newly added items is removed from the back of the array.
Here the desired functionality getItemsAdded(arr1, arr2)
function:
JavaScript
1
7
1
// Desired output for 'getItemsAdded()' function
2
console.log(getItemsAdded(arr1, arr2)); // [ 'a', 'b' ]
3
console.log(getItemsAdded(arr3, arr4)); // [ 'q', 'r' ]
4
console.log(getItemsAdded(arr5, arr6)); // [ 'a', 'b', 'q' ]
5
// New
6
console.log(getItemsAdded(arr7, arr8)); // [ 'a', 'b' ]
7
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.
Advertisement
Answer
Code can tell more words, Then my silly explanation…
JavaScript
1
29
29
1
// Input 1
2
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
3
const arr2 = ['a', 'b', 'a', 'b', 'c', 'd', 'e', 'f', 'g']; // added 'a' and 'b' in front
4
// Input 2
5
const arr3 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
6
const arr4 = ['q', 'r', 'a', 'b', 'c', 'd', 'e', 'f', 'g']; // added 'q' and 'r' in front
7
// Input 3
8
const arr5 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
9
const arr6 = ['a', 'b', 'q', 'a', 'b', 'c', 'd', 'e', 'f']; // added 'a' 'b' and 'q' in front
10
11
const arr7 = ['a', 'b', 'a', 'b', 'c', 'd', 'e', 'f', 'g'];
12
const arr8 = ['a', 'b', 'a', 'b', 'a', 'b', 'c', 'd', 'e']; // added 'a' and 'b' in front
13
14
// Desired output for 'diff()' function
15
console.log([getItemsAdded(arr1, arr2)]); // [ 'a', 'b' ]
16
console.log([getItemsAdded(arr3, arr4)]); // [ 'q', 'r' ]
17
console.log([getItemsAdded(arr5, arr6)]); // [ 'a', 'b', 'q' ]
18
console.log([getItemsAdded(arr7, arr8)]); // [ 'a', 'b' ]
19
20
function startsWith(arr1, arr2) {
21
for (let i = 0; i < arr1.length; i++)
22
if (arr1[i] != arr2[i])
23
return false
24
25
return true
26
}
27
function* getItemsAdded(arr1, arr2) {
28
while (!startsWith(arr2, arr1)) yield arr2.shift()
29
}