Javascript 使用我自己的reduce函数检查数组相交
我想创建一个小应用程序,它可以检查数组中的相交值,并将这些数组减少到一个只包含相交数字的新数组中。我可以使用内置的原型方法来完成这项工作,但我想用自己定义的函数来完成Javascript 使用我自己的reduce函数检查数组相交,javascript,arrays,functional-programming,reduce,Javascript,Arrays,Functional Programming,Reduce,我想创建一个小应用程序,它可以检查数组中的相交值,并将这些数组减少到一个只包含相交数字的新数组中。我可以使用内置的原型方法来完成这项工作,但我想用自己定义的函数来完成 constforeach=(数组,回调)=>{ 对于(var i=0;i{ 累加器=初始值 常量还原函数=(el)=>{ 累加器+=回调(el) } forEach(数组,reduceFunction) 回流蓄能器 } const intersectionWithReduce=(…数组)=>{ currentValue=[] 减
constforeach=(数组,回调)=>{
对于(var i=0;i{
累加器=初始值
常量还原函数=(el)=>{
累加器+=回调(el)
}
forEach(数组,reduceFunction)
回流蓄能器
}
const intersectionWithReduce=(…数组)=>{
currentValue=[]
减少(数组,el=>currentValue+=arrays.filter(currentValue.includes(el)),currentValue)
返回电流值
}
log(intersectionWithReduce([1,2,3,20],[15,88,1,2,7],[1,10,3,2,5,20]);
//[1,2]的预期产出
//实际输出类型错误:false不是函数
如果要模拟reduce
的功能,请使用(至少)两个参数调用callback
:当前累加器和正在迭代的当前项。然后将结果分配给累加器,并继续,直到数组完全迭代
因为您想在这里找到一个交集,所以最好不要传递初始值,而是默认情况下将数组的第一项作为累加器(就像array.prototype.reduce
所做的那样),在每次迭代中,调用累加器上的.filter
,针对其他数组是否包含元素进行测试:
constreduce=(数组、回调、initValue)=>{
设i=0;
让累加器=initValue!==未定义?initValue:(i++,数组[0]);
对于(;i{
返回减少(数组,(累加,累加)=>accum.filter(累加=>arr.includes(累加));
}
log(intersectionWithReduce([1,2,3,20],[15,88,1,2,7],[1,10,3,2,5,20])代码>您可以尝试这种简单的方法,而无需使用reduce
看:
2
不在第三个参数数组中吗?如果它不相交,为什么要包含它?我更新了thank youcurrentValue。includes(el)
返回一个布尔值。您正在将其传递给filter()
,它需要一个函数。因此acum
是累加器值,arr
是另一个数组的值,这是什么其他数组?是位于运行intersectionWithReduce
中的下一个数组吗?arr
是正在迭代的当前子数组-例如,[1,2,3,20]
,或[15,88,1,2,7]
const intersectionWithReduce = (...arrays) => (
arrays.map(arrElm => // array of arrays, arrays[0] = [1, 2, 3, 20]
arrElm.filter(arrElm => // filtering for equals
arrays.every(elm =>
elm.includes(arrElm) // only evaluate if this item is present in every other array
)
)
)[0]
)
/* /\
* Here it's [0] because doesn't matter the position,
* all the remaining arrays will be the same.
* In this case without this part the result would be [[1, 2], [1, 2], [1, 2]]
*/
console.log(intersectionWithReduce([1, 2, 3, 20], [15, 88, 1, 2, 7], [1, 10, 3, 2, 5, 20]))
// output [1, 2]