2017-02-27 49 views
-2

我有兩個數組apple = [1,5,10,15,20]bottle = [1,5,10,15,20,25]使用lodash或任何JavaScript函數,我想要一個數組c與唯一元素c= [25]。更確切地說,當'apple'數組與'bottle'數組進行比較時,我需要所有元素的列表,以顯示唯一的元素/比較兩個對象的數組javascript並將不匹配的數組元素使用下劃線或lodash

+4

['變種C = _.difference(瓶,蘋果);'](https://lodash.com/docs/4.17.4#difference) – 4castle

回答

1

您可以使用reduce()filter()創建您自己的函數。

var apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] 
 

 
function diff(a1, a2) { 
 
    //Concat array2 to array1 to create one array, and then use reduce on that array to return 
 
    //one object as result where key is element and value is number of occurrences of that element 
 
    var obj = a1.concat(a2).reduce(function(result, element) { 
 
    result[element] = (result[element] || 0) + 1 
 
    return result 
 
    }, {}) 
 
    
 
    //Then as function result return keys from previous object where value is == 1 which means that 
 
    // that element is unique in both arrays. 
 
    return Object.keys(obj).filter(function(element) { 
 
    return obj[element] == 1 
 
    }) 
 
} 
 

 
console.log(diff(apple, bottle))

較短的版本與ES6箭頭功能相同的代碼。

var apple = [1,5,10,15,20], bottle = [1,5,10,15,20,25] 
 

 
function diff(a1, a2) { 
 
    var obj = a1.concat(a2).reduce((r, e) => (r[e] = (r[e] || 0) + 1, r), {}) 
 
    return Object.keys(obj).filter(e => obj[e] == 1) 
 
} 
 

 
console.log(diff(apple, bottle))

+0

可能希望寫多一點自我記錄代碼.. – mhodges

+1

@mhodges我更新了我的答案。 –

1

你可以使用Array#filter與對面陣列的Set

該建議使用complement函數,如果元素a不在集合b中,則返回true

對於對稱差異,必須在雙方都使用回調過濾。

function getComplement(collection) { 
 
    // initialize and close over a set created from the collection passed in 
 
    var set = new Set(collection); 
 
    // return iterator callback for .filter() 
 
    return function (item) { 
 
     return !set.has(item); 
 
    }; 
 
} 
 
var apple = [1,5,10,15,20], 
 
    bottle = [1,5,10,15,20,25], 
 
    unique = [ 
 
     ...apple.filter(getComplement(bottle)), 
 
     ...bottle.filter(getComplement(apple)) 
 
    ]; 
 

 
console.log(unique);

+0

您通常會寫出非常清晰和簡潔的答案,但我必須說,即使作爲一名經驗豐富的ES6開發人員,您在這裏使用箭頭函數和單字母變量名稱也很神祕而且很難閱讀。僅僅因爲ES6給了我們箭頭函數,並不意味着我們必須用它來將代碼塞進一行。 – mhodges

+0

函數關鍵字有問題嗎? – mhodges

+0

@mhodges,不,功能很好。但你對這個問題意味着什麼? –

相關問題