比较2个数组并find与Ramda相同的值

我最近爱上了函数式编程,并开始学习ramda.js,但我似乎还没有进入function思维。 我有2个string数组(他们实际上是拆分string),我想find第一个string中有多less个字符等于在第二个string中的相同位置。 我必须做一些非常简单的事情:

let counter = 0 for(let i = 0; i < array.length; i++){ if(firstArray[i] === secondArray[i]) counter++ } 

但我将如何使用ramda呢?

“…使用rambda”

这里有一个方法可以做到 – 有无数的其他方法…

 let a = Array.from('abcdefg') let b = Array.from('abcxyzg') const countEqualChars = (a,b) => R.sum(R.zipWith(R.equals, a, b)) countEqualChars(a,b); // => 4 

但是…

这基本上是你的函数式编程的错误方法。 忘记Rambda,直到你有一个很好的理解如何以function的方式推理程序。 如果你不知道Rambda的基本层面是如何工作的,你将永远无法体会到Rambda的便利。

首先学习recursion作为for/while循环的替代方法。 循环没有任何问题,但是recursion可以让你有时候以更好的方式expression事物。

 let a = Array.from('abcdefg') let b = Array.from('abcxyzg') const countEqualChars = ([x,...xs],[y,...ys]) => { if (x === undefined || y === undefined) return 0 else if (x === y) return 1 + countEqualChars (xs,ys) else return countEqualChars (xs,ys) } console.log (countEqualChars (a,b)) // 4 

我无法与其他竞争者,优秀的答案,但不要忘记array原型有许多有用的方法,如filterreduce

 var countMatches = (a, b) => a.reduce((sum, c, i) => b[i] === c ? ++sum : sum , 0); var set1 = "1234678".split(""); var set2 = "1234568".split(""); console.log(countMatches(set1, set2));