I am working on a project with an array of values that could possibly change every 30 seconds. I need to compare the first array
to the current array
of values every time this runs and return the difference between the values ONLY if a value is removed.
For example if array1 = [12, 14, 16]
and array2 = [12, 16, 18]
, then I need to return 14
and do something with it. What would be the best way to accomplish this?
This is my current code, but it returns any difference between the two arrays:
function diffArr (array1, array2) {
const temp = [];
array1 = array1.toString().split(',').map(Number);
array2 = array2.toString().split(',').map(Number);
for (var i in array1) {
if(!array2.includes(array1[i])) temp.push(array1[i]);
}
for(i in array2) {
if(!array1.includes(array2[i])) temp.push(array2[i]);
}
return temp.sort((a,b) => a-b);
}
Try this:
const array1 = [12, 14, 16, 20, 10]
const array2 = [12, 16, 18]
const diffArr = (array1, array2) => {
const temp = array1.filter(ele => !array2.includes(ele))
return temp.sort((a,b) => a-b);
}
console.log(diffArr(array1, array2)) // output = [ 10, 14, 20 ]