JavaScript. How to Compare Input Arrays

后端 未结 6 1996
隐瞒了意图╮
隐瞒了意图╮ 2021-01-15 14:13

I\'m stuck with this problem for 3 days now... Someone please help me.

Challenge 5
Construct a function intersection

6条回答
  •  不知归路
    2021-01-15 14:20

    First try to find out the intersection of two arrays which is the base problem. Then try to build up for variable number of arrays passed as arguments for intersection. You can use reduce() for doing that.

    function intersectionOfTwoArrays(arr1, arr2)
    {
       return arr1.filter(x => arr2.some(y => y === x)); 
    }
    
    
    function intersection(...arrayOfArrays)
    {
    	return arrayOfArrays
    	       .reduce((a, b) => intersectionOfTwoArrays(a, b));
    }
    
    intersection(
    [5, 10, 15, 20], 
    [15, 88, 1, 5, 7], 
    [1, 10, 15, 5, 20]
    );

提交回复
热议问题