var fruits_2016 = [
[
'22',
'apple',
'red'
],
[
'23',
'orange',
'orange'
],
[
'69',
'cucumber',
'darkgray'
],
];
var fruits_2017 = [
[
'22',
'apple',
'red'
],
[
'23',
'orange',
'orange'
],
[
'69',
'cucumber',
'darkgray'
],
[
'31',
'potato',
'brown'
],
];
var fruits_2018 = [
[
'22',
'apple',
'red'
],
[
'23',
'orange',
'orange'
],
[
'11',
'opium',
'deepblue'
],
];
var sorted_fruits_2016 = fruits_2016.sort(sortById);
var sorted_fruits_2017 = fruits_2017.sort(sortById);
var sorted_fruits_2018 = fruits_2018.sort(sortById);
var result_2016_2017 = compare(sorted_fruits_2016, sorted_fruits_2017);
var result_2017_2018 = compare(sorted_fruits_2017, sorted_fruits_2018);
function compare(oldArr, newArr) {
var deleted = [], added = [], notChanged = [];
var innerIndex = 0;
if (!newArr.length) {
return {
added: added,
deleted: oldArr,
notChanged: notChanged
};
}
for (var i = 0; i < newArr.length; i++) {
if (innerIndex >= oldArr.length - 1) {
added.push(newArr[i]);
continue;
}
for (var j = innerIndex; j < oldArr.length; j++) {
var newElId = newArr[i][0];
var oldElId = oldArr[j][0];
if (newElId > oldElId) {
deleted.push(oldArr[j]);
} else if (newElId < oldElId) {
added.push(newArr[i]);
innerIndex = j;
break;
} else {
notChanged.push(newArr[i]);
innerIndex = j + 1;
break;
}
}
}
return {
deleted: deleted,
added: added,
notChanged: notChanged
};
}
function sortById(a, b) {
return a[0] - b[0];
}
var result = compare(fruits_2016, fruits_2017);
console.log('result', result);
function compare(oldArr, newArr) {
var sortedOldArr = oldArr.sort(sortById);
var sortedNewArr = newArr.sort(sortById);
return compareSorted(sortedOldArr, sortedNewArr);
}
function compareSorted(oldArr, newArr) {
var deleted = [], added = [], notChanged = [];
var innerIndex = 0;
if (!newArr.length) {
return {
added: added,
deleted: oldArr,
notChanged: notChanged
};
}
for (var i = 0; i < newArr.length; i++) {
if (innerIndex >= oldArr.length - 1) {
added.push(newArr[i]);
continue;
}
for (var j = innerIndex; j < oldArr.length; j++) {
var newElId = newArr[i][0];
var oldElId = oldArr[j][0];
if (newElId > oldElId) {
deleted.push(oldArr[j]);
} else if (newElId < oldElId) {
added.push(newArr[i]);
innerIndex = j;
break;
} else {
notChanged.push(newArr[i]);
innerIndex = j + 1;
break;
}
}
}
return {
deleted: deleted,
added: added,
notChanged: notChanged
};
}
function sortById(a, b) {
return a[0] - b[0];
}