JavaScript.如何比较输入数组 [英] JavaScript. How to Compare Input Arrays

查看:77
本文介绍了JavaScript.如何比较输入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这个问题上停留了三天了……请有人帮助我.

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

挑战5
构造一个比较输入数组的函数intersection,并返回一个包含所有输入中包含的元素的新数组.

Challenge 5
Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.

function intersection(arrayOfArrays) {

}

console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));

// should log: [5, 15]

推荐答案

您可以通过仅检查另一个数组是否包含该值来进行过滤来缩小数组.

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 :

如果未提供initialValue,则accumulator将等于数组中的第一个值,而currentValue将等于第二个值.

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.

回调

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

过滤数组a.如果数组b包含a的值,则该值v将包含在accumulator中,以用于下一次迭代或最终结果.

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]]));

这篇关于JavaScript.如何比较输入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆