2014-10-12 93 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是正确的,但我分享展示一个潜在的扩张食物,当独特的需要被'调整'