2014-12-13 78 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