簡體   English   中英

如何在Node.js中的兩個數組之間獲得添加和刪除?

[英]How to get additions and deletions between two arrays in 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

我想得到以下輸出:-項目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
}

如果元素具有隨機位置,那么您唯一可以做的就是遍歷數組以確保添加或刪除了哪些元素,或者您也可以使用下划線lib(它也為節點提供了一個包)

函數是:

_.difference(array, *others) 

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM