2016-08-23 53 views
1

使用lodash,是否可以從另一個數組中刪除一個數組,同時避免刪除重複?不使用lodash差異刪除重複

我目前使用_.difference

// this returns [4] 
_.difference([1, 1, 1, 2, 2, 2, 3, 4], [1, 2, 3]) 

// I want it to return [1, 1, 2, 2, 4] 
+1

你的問題很曖昧。目前還不清楚每個元素應該從第一個數組中刪除哪個元素。假設你有這些數組:'[1,1,2,2,1,2,3,4],[1,2,3]'。你期望的結果是什麼? – hindmost

+0

嗯,好點。我想刪除第二個數組中每個項目的第一個實例。所以這將是[1,2,1,2,3,4] – Finnnn

+0

AFAIK lodash沒有這樣的方法可供使用。我會建議使用嵌套for循環。 – hindmost

回答

3

這是我怎麼會做純JS

var arr1 = [1, 1, 1, 2, 2, 2, 3, 4], 
 
    arr2 = [1, 2, 3], 
 
    result = arr2.reduce((p,c) => {var idx = p.indexOf(c); 
 
           return idx === -1 ? p : (p.splice(idx,1),p)}, arr1); 
 
console.log(result);

1

基於從@hindmost評論,我用了一個循環。

var tempArray = [1,1,1,2,2,2,3,3,1,2] 

_.each([1, 2, 3], function(value) { 
    tempArray.splice(tempArray.indexOf(value), 1); 
}); 
1

是的,它會返回4,因爲_.difference返回過濾values.I嘗試Java腳本的新數組解。希望它能幫助你。

function keepDuplicate(array1, array2){ 
    var occur; 
    var indexes = []; 
    _.each(array2, function(value){ 
    _.each(array1, function(ar1value, index){ 
    if(value === ar1value){ 
     occur = index; 
    } 
    }); 
    indexes.push(occur); 
    }); 
    _.each(indexes, function(remove, index){ 
    if(index === 0){ 
    array1.splice(remove, 1); 
    } 
    else{ 
    remove = remove-index; 
    array1.splice(remove,1); 
    } 
}); 
return array1; 
} 

keepDuplicate([1, 1, 1, 2, 2, 2, 3, 4], [1, 2, 3])

它將返回[1, 1, 2, 2, 4]

+0

這段代碼將從第二個數組中的第一個數組中刪除單個值。 –