Array.prototype.every() every()
方法测试数组的所有元素是否都通过了指定函数的测试
const all = (arr, fn = Boolean) => arr.every(fn);
all([4, 2, 3], x => x > 1); // true all([1, 2, 3]); // true
const allEqual = arr => arr.every(val => val === arr[0]);
allEqual([1, 2, 3, 4, 5, 6]); // false allEqual([1, 1, 1, 1]); // true
some()
方法测试是否至少有一个元素通过由提供的函数实现的测试。
const any = (arr, fn = Boolean) => arr.some(fn);
any([0, 1, 2, 0], x => x >= 2); // true any([0, 0, 1, 0]); // true
根据给出的函数找出两个数组中的差集
const differenceBy = (a, b, fn) => { const s = new Set(b.map(fn)); return a.filter(el => !s.has(fn(el))); };
const superHeroCompany = [
{ name: 'xiaoer', job: '程序员' },
{ name: 'xiaosi', job: '图书管理员', },
{ name: 'menty', job: '会计' },
]
const happyCompany = [
{ name: 'xiaofu', job: '程序员' },
{ name: 'panghu', job: '会计' },
]
const diffUsers = differenceBy(superHeroCompany, happyCompany, v => v.job)
根据条件将数组分成两个集合。
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []])
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]
https://30secondsofcode.org/