2014-12-13 25 views

回答

1

這已經被問和之前1000次回答,但既然你問了一個功能的編程解決方案,在這裏你去:

head = function(ls) { return ls[0] }; 
tail = function(ls) { return ls.slice(1) }; 
empty = function(ls) { return ls.length == 0 }; 
cons = function(a, b) { return [a].concat(b) }; 

has = function(x, ls) { 
    return empty(ls) ? false : head(ls) == x || has(x, tail(ls)); 
}; 

_uniq = function(ls, seen) { 
    return empty(ls) ? [] : 
     has(head(ls), seen) ? 
      _uniq(tail(ls), seen) : 
      cons(head(ls), 
       _uniq(tail(ls), 
        cons(head(ls), seen))); 
}; 

uniq = function(ls) { 
    return _uniq(ls, []); 
}; 

console.log(uniq([1,1,2,3,1,2,5])); // [1,2,3,5] 

這是純功能性的解決方案,如要求(事實上,nub直口)。對於實際的之一,請考慮其中一個答案over here

+0

這就是我一直在尋找的,謝謝! – Roman 2014-12-13 16:01:24

1

好吧,如果你不擔心的表現,我會用Array.prototype.filterArray.prototype.indexOf,這樣

function toUnique(array) { 
    return array.filter(function(currentItem, index) { 
     return (index === array.indexOf(currentItem)); 
    }); 
} 

console.log(toUnique([1, 1, 2, 3, 4, 4])); 
# [ 1, 2, 3, 4 ] 

如果你可以使用任何其他圖書館,你可以使用lodash's uniq function,這樣

_.uniq([1, 1, 2, 3, 4, 4]); 
// → [1, 2, 3, 4] 

它還可以接受的事實是,輸入的優勢數組已經排序。所以,你可能需要調用它像這樣

_.uniq([1, 1, 2, 3, 4, 4], true); 
// → [1, 2, 3, 4] 
1

看看在Ramda功能的JavaScript libriary的uniq功能。

R.uniq([1, 1, 2, 1]); //=> [1, 2] 
R.uniq([{}, {}]);  //=> [{}, {}] 
R.uniq([1, '1']);  //=> [1, '1'] 

您可以使用函數從libriary或檢查source code ...

function uniq(list) { 
    var idx = -1, len = list.length; 
    var result = [], item; 
    while (++idx < len) { 
     item = list[idx]; 
     if (!_contains(item, result)) { 
      result[result.length] = item; 
     } 
    } 
    return result; 
}; 
+0

這個很棒!有沒有任何具有相同功能的FRP庫? – Roman 2014-12-13 15:55:01