2017-01-02 127 views
1

我很困惑。本質上,我試圖創建一個函數,它將一個數字作爲參考和一個數組,並且找到等於零的組合(參考數字和數組中的兩個),但不會在subArray中有任何重複的組合。避免插入子數組重複項

function helper(number, arr){ 
    console.log(arr, 'this is arr') 
    let answer = []; 
    let subArray = [] 
    for(let i = 0; i < arr.length; i++){ 
    for(let y = i + 1; y < arr.length; y++){ 
     var newCombo = [arr[i], arr[y]] 
     subArray.push(newCombo) <-- avoid duplicates here 
    } 
    } 
    subArray.forEach(combo =>{ 
    var referenceAndArray = [number].concat(combo) 
    //result will check it adds up to zero 
    var result = referenceAndArray.reduce((accum, value) =>{ 
     return accum += value; 
    },0) 

    if(result === 0){ 
     answer.push(referenceAndArray) 
    } 
    }) 

    return answer 
} 

helper(-1, [-1,-1,0,1,2] --> [ [-1, 0, 1 ], [-1, -1, 2] ] 

我們可以假設數組從一開始就

使用Array.includes我試圖測試,但它似乎不具有子陣列以及工作排序。

+0

發現僅有1個組合或者所有可能的組合? – luanped

+0

找到所有可能的組合,沒有任何重複 – Alejandro

+1

數組通過身份而不是數值進行比較,所以'[]!== []' – elclanrs

回答

1

由於數組是通過身份而不是值進行比較的,因此您可以加入數組內容並比較它是否已經存在。

基本上替換subArray.push(newCombo) <-- avoid duplicates here

let exists = subArray.some(combo => combo.join() === newCombo.join()); if (!exists) { subArray.push(newCombo); }

例如,如果你有一個包含[[-1, -1, 2], [-1, 0, 1]]陣列和當你發現另一組合[-1, -1, 2];在插入它之前,我們檢查它是否已經存在,並且只有在沒有時才添加它。要做到這一點,將通過數組循環檢查字符串「-1,-1,2」是否已經使用.some()(只要數組中的1個元素匹配,就是true)。在這種情況下,我們比較「-1,-1,2」和「-1,0,1」,因此exists爲真,因此我們將其添加到數組中。

+0

工作很好!我不知道'Array.prototype.some'。 Def有用! – Alejandro

1

您可以使用Set,並存儲對的字符串版本,這將保證不存儲重複項。這將工作速度比在陣列

這裏查找元素是用最少的適應您的代碼,使其工作方式:

function helper(number, arr){ 
 
    console.log(JSON.stringify(arr), 'this is arr'); 
 
    let answer = []; 
 
    let subArray = []; 
 
    let uniques = new Set; 
 
    for(let i = 0; i < arr.length; i++){ 
 
    for(let y = i + 1; y < arr.length; y++){ 
 
     uniques.add(arr[i] + ',' + arr[y]); // add primitive (string) to set. 
 
    } 
 
    } 
 
    uniques.forEach(s => { 
 
    // now get the number parts of the stored string: 
 
    var referenceAndArray = [number].concat(s.split(',').map(Number)); 
 
    //result will check it adds up to zero 
 
    var result = referenceAndArray.reduce((accum, value) =>{ 
 
     return accum += value; 
 
    }, 0) 
 

 
    if(result === 0){ 
 
     answer.push(referenceAndArray); 
 
    } 
 
    }) 
 

 
    return answer; 
 
} 
 

 
var result = helper(-1, [-1,-1,0,1,2]); //--> [ [-1, 0, 1 ], [-1, -1, 2] ] 
 
console.log(JSON.stringify(result));