简体   繁体   English

如何在Node.js中的两个数组之间获得添加和删除?

[英]How to get additions and deletions between two arrays in Node.js?

I have 2 arrays that change once in a while. 我有2个数组,有时会更改一次。 I want to compare them and get the additions & deletions between the first, source array and the second array. 我想比较它们,并获得第一个,源数组和第二个数组之间的添加和删除。

Additions/deletions can occur at the middle of the array (not necessarily at the edges). 添加/删除可以发生在数组的中间(不一定在边缘)。

For example, from these arrays: 例如,从这些数组中:

Array 1
Item A | Item B | Item C | Item D | Item E

Array 2
Item A | Item Z | Item C | Item D | Item E

I would like to get the following output: - Item B was removed - Item Z was added 我想得到以下输出:-项目B已删除-项目Z已添加

What is the best way to deal with this issue? 解决此问题的最佳方法是什么?

If the item type is string, then follow this 如果项目类型是字符串,请遵循此

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
}

If the elements have random positions, the only think you can do is traverse the array in order to get sure of what elements are add or removed or you can use the underscore lib it has a package for node, too 如果元素具有随机位置,那么您唯一可以做的就是遍历数组以确保添加或删除了哪些元素,或者您也可以使用下划线lib(它也为节点提供了一个包)

the function is: 函数是:

_.difference(array, *others) 

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM