碎片时间学编程「299]:计算基于函数的数组差异

从比较器函数不返回的数组中过滤掉所有值为true 的值。
使用Array.prototype.filter()和Array.prototype.findIndex()方法找到合适的值。
省略最后一个参数 comp以使用默认的严格相等比较器。
JavaScript
const differenceWith = (arr, val, comp = (a, b) => a === b) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
示例:
differenceWith( [1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b) ); // [1, 1.2] differenceWith([1, 1.2, 1.3], [1, 1.3, 1.5]); // [1.2]
更多内容请访问我的网站:https://www.icoderoad.com