函数式JavaScript:生成唯一值数组

Functional JavaScript: Produce array of unique values

本文关键字:唯一 数组 JavaScript 函数      更新时间:2023-09-26

使用JavaScript中的函数式编程从另一个数组中生成唯一值数组的方法是什么?

这应该做:toUnique([1,1,2,3,4,4]) => [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 中的函数或检查源代码...

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;
};

这在之前已经被问了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的直端口)。对于实际的问题,请考虑此处的答案之一。

好吧

,如果你不担心性能,我会使用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 的 uniq 函数,像这样

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

它还可以利用输入数组已经排序的事实。因此,您可能希望像这样调用它

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