使用JavaScript中的函数式编程从另一个数组中生成唯一值数组的方法是什么?功能性JavaScript:生成唯一值的数组
这应该做的:toUnique([1,1,2,3,4,4]) => [1,2,3,4]
使用JavaScript中的函数式编程从另一个数组中生成唯一值数组的方法是什么?功能性JavaScript:生成唯一值的数组
这应该做的:toUnique([1,1,2,3,4,4]) => [1,2,3,4]
这已经被问和之前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]
好吧,如果你不担心的表现,我会用Array.prototype.filter
和Array.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]
看看在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;
};
这个很棒!有没有任何具有相同功能的FRP库? – Roman 2014-12-13 15:55:01
这就是我一直在寻找的,谢谢! – Roman 2014-12-13 16:01:24