JavaScript. How to Compare Input Arrays

后端 未结 6 1992
隐瞒了意图╮
隐瞒了意图╮ 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:33

    You could reduce the array by filtering with just checking if the other array contains the value.

    This works for arrays with unique values.

    Array#reduce:

    If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

    The callback

    a.filter(v => b.includes(v))
    

    filters array a. If the array b includes the value of a, then this value v is included in the accumulator for the next iteration or as final result.

         accumulator            currentValue           new accumulator
              a                       b                    result
    --------------------    --------------------    --------------------
    [     5, 10, 15, 20]    [15, 88,  1,  5,  7]    [             5, 15]
    [             5, 15]    [ 1, 10, 15,  5, 20]    [             5, 15]
    

    function intersection(arrayOfArrays) {
        return arrayOfArrays.reduce((a, b) => a.filter(v => b.includes(v)));
    }
    
    console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));

提交回复
热议问题