Ron*_*Ron 0 javascript arrays node.js
我有2个阵列偶尔会改变一次.我想比较它们并获得第一个,源数组和第二个数组之间的添加和删除.
添加/删除可以发生在阵列的中间(不一定在边缘).
例如,从这些数组:
Array 1
Item A | Item B | Item C | Item D | Item E
Array 2
Item A | Item Z | Item C | Item D | Item E
Run Code Online (Sandbox Code Playgroud)
我想得到以下输出: - 项目B被删除 - 项目Z被添加
处理这个问题的最佳方法是什么?
如果项类型是字符串,则按照此操作
var getAddedorRemovedItem = function (sourceArray1, sourceArray2) {
var added = [], removed = [];
sourceArray1.forEach(function(item){
if (sourceArray2.indexOf(item) == -1) {
removed.push(item);
}
});
sourceArray2.forEach(function (item) {
if (sourceArray1.indexOf(item) == -1) {
added.push(item);
}
});
// here added array contain all new added item and removed contain all removed item;
// do acc. to whatever you want to get outpur
}
Run Code Online (Sandbox Code Playgroud)