Returns the difference between two arrays.
Create a
Setfromb, then useArray.filter()onato only keep values not contained inb.const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; // difference([1,2,3], [1,2,4]) -> [3]
返回两个数组的不同。
创建一个b数组的集合,然后使用Array.filter()对a数组进行过滤,过滤出不存在于数组b的元素。
➜ code cat difference.js
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
}
console.log(difference([1, 2, 3], [1, 2, 4]));
➜ code node difference.js
[ 3 ]
关键点是主客体,这里主体应该是第一个数组,也就是a,客体是数组b,返回的是不在主体a里的数组元素。类似于集合的a - b,不同点是a、b数组都可以有重复的元素存在,而集合不允许重复元素存在。
这逻辑是很清晰的,先把b数组转成集合存到s中,然后去filter数组a,只要把不存在于s集合中的元素返回即可。记住filter返回的是一个数组。
Filters out all values from an array for which the comparator function does not return
true.Use
Array.filter()andArray.find()to find the appropriate values.const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))) // differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2]
从一个数组中筛选出所有不满足指定比较方法运算结果为true的元素值的数组。
使用Array.filter()和Array.find()来找出适当的值。
➜ code cat differenceWith.js
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)));
console.log(differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)));
➜ code node differenceWith.js
[ 1, 1.2 ]
和difference类似,主客体还是第一个数组arr。
我们可以先把意思进行拆分。
comp运行结果为trueval.find()去寻找comp(a, b)(a 是 arr 元素,b 是 val 元素)运行结果为true的值arr不要上面第 2 点中运行结果为true的值通俗点就是说去遍历数组arr的所有元素,然后在数组val里寻找comp运算结果不为 true 的值。因为val.find()方法如果找到就返回该值,否则返回undefined,此时!val.find()就是true,arr.filter()正是需要这样运算结果的值。
Returns all the distinct values of an array.
Use ES6
Setand the...restoperator to discard all duplicated values.const distinctValuesOfArray = arr => [...new Set(arr)]; // distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
返回数组去重结果。
使用ES6的集合Set和ES6的扩展运算符…把重复的元素排除掉。
➜ code cat distinctValuesOfArray.js
const distinctValuesOfArray = arr => [...new Set(arr)];
console.log(distinctValuesOfArray([1, 2, 2, 3, 4, 4, 5]));
➜ code node distinctValuesOfArray.js
[ 1, 2, 3, 4, 5 ]
实际上ES6的集合Set干的事,没啥可说。
全文太长请戳下边:
个人翻译水平有限,欢迎大家在 issues 上批评指正。JavaScript30 秒, 从入门到放弃之 Array (二)
微信公众号:JavaScript30 秒, 从入门到放弃之 Array (二)
1
bramblex 2017 年 12 月 26 日 via iPhone
对于一切拿 js 讲函数式的,我算是又爱又恨…
|
4
GabrielChen 2017 年 12 月 26 日
这项目最近在 github 上好火
|
5
supermao OP @GabrielChen 相当的火,虽然说代码的效率上根本无法和 underscore 和 lodash 比,但是写得少啊,看起来逻辑就很清晰,很美
|