JavaScript.如何比较输入数组 [英] JavaScript. How to Compare Input Arrays
问题描述
我已经在这个问题上停留了三天了……请有人帮助我.
I'm stuck with this problem for 3 days now... Someone please help me.
挑战5
构造一个比较输入数组的函数intersection
,并返回一个包含所有输入中包含的元素的新数组.
Challenge 5
Construct a functionintersection
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.
如果未提供
initialValue
,则accumulator
将等于数组中的第一个值,而currentValue
将等于第二个值.
If no
initialValue
is provided, thenaccumulator
will be equal to the first value in the array, andcurrentValue
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屋!