用下划线重写交集 - 理解参数数组

时间:2015-07-28 18:47:02

标签: javascript functional-programming underscore.js

我在下面写的函数是下划线的交集,从头开始重写。现在,这只适用于两个数组。我怎样才能让它按原样运行,但是有任意数量的参数?

  _.intersection = function() {

            var argumentsArray = Array.prototype.slice.call(arguments);

            return _.filter(argumentsArray[0], function(val) {
                return _.indexOf(argumentsArray[1], val) != -1
            });

        };

2 个答案:

答案 0 :(得分:2)

您可以对参数数组执行reduce操作,如下所示:

_.intersection = function() {
  var argumentsArray = Array.prototype.slice.call(arguments);

  return _.reduce(argumentsArray, function (intersectedArray, currentArray) {
    return _.filter(intersectedArray, function(val) {
      return _.indexOf(currentArray, val) !== -1
    });
  });
};

查看演示here

答案 1 :(得分:1)

这不是我的工作 https://jsfiddle.net/i_like_robots/KpCt2/

 var alpha = [1, 2, 3, 4, 5, 6],
        beta = [4, 5, 6, 7, 8, 9];

    $.arrayIntersect = function(a, b)
    {
        return $.grep(a, function(i)
        {
            return $.inArray(i, b) > -1;
        });
    };

    window.console && console.log( $.arrayIntersect(alpha, beta) );

http://2ality.com/2015/01/es6-set-operations.html

function unionArray(...arr){
    let union = new Set(arr);
    return union;
}


function Intersection(a,b){

    var a = new Set(a);
    var b = new Set(b);
    let union = new Set( [...a].filter(x => b.has(x)));
    return union;
}


function Difference(a,b)  {
    var a = new Set(a);
    var b = new Set(b);
    let union = new Set( [...a].filter(x => !b.has(x)));
    return union;
}