2014-10-12 54 views
0

我需要從以下2D陣列的2D陣列的只有唯一值:如何獲得

[[選項10,2.0],[選項10,2.0],[選項9,1.0],[選項7,1.0]]

[[選項10,2.0],[選項9,1.0],[選項7,1.0]]

我發現這個職位(Splitting a 2D array using some() , by date, avoiding duplicates. Just want 1 unique email, not row. Where am i wrong here?),其具有一種獲得獨特價值的非常有效的方法,但我無法弄清楚如何將其應用於我的情況。

回答

1

您的用例比您所指的更簡單。

嘗試這個,例如:

function myFunction() { 
    var source = [['Option 10', 2], ['Option 10', 2], ['Option 9', 1], ['Option 7', 1]]; 
    var dest = []; 
    dest.push(source[0]); 
    for(var n = 1 ; n< source.length ; n++){ 
    if(dest.join().indexOf(source[n].join()) == -1){dest.push(source[n])}; 
    } 
    Logger.log(dest); 
} 
1

因爲「獨一無二」並不總是簡單的描述,我經常使用的模式是,實際上,使用ES5陣圖塞爾的正確答案的變化/過濾功能。

編輯版:

function hash(arr) { 

    // in this case the hash method is the same as Serge's Array.join() method, 
    but could be customised to suit whatever condition you need to generate 
    bespoke comparators such as where `1 + 3` should match `2 + 2`, or where 
    particular columns in the array can be omitted 

    return arr.join(); 
} 

function myFunction() { 
    var source = [['Option 10', 2], ['Option 10', 2], ['Option 9', 1], ['Option 7', 1]]; 
    var hash = source.map(
    function (row) { 
     return hash(row); 
    } 
); 

    source = source.filter(
    function (filterRow, i) { 
     return hash.slice(0, i).indexOf(hash(filterRow)) < 0; 
    } 
); 

    Logger.log(source); 
} 

我只包含這是有些時候,你的比較可能需要彎曲一點。在你的例子中,這並不重要,這就是爲什麼Serge's是正確的,但我分享展示一個潛在的擴張食物,當獨特的需要被'調整'