简体   繁体   中英

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

I have 2 arrays that change once in a while. 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

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

the function is:

_.difference(array, *others) 

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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