3分鐘速學:js數組操作技巧

01:判斷數組每一項都符合某個條件

實現:採用Array.prototype.every()即可完成

const all = (arr, fn = Boolean) => arr.every(fn);

測試

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true

02:判斷數組至少有一項都符合某個條件

實現:

const any = (arr, fn = Boolean) => arr.some(fn);

測試

any([0, 1, 2, 0], x => x >= 2); // true
any([0, 0, 1, 0]); // true

03:將數組分成2組

實現

const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);

測試

bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]

04:統計數組,滿足某個條件

實現

const countBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});

測試

countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}

05:比較2個數組差異

實現

const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};

測試

difference([1, 2, 3], [1, 2, 4]); // [3]

06:按條件比較2個數組差異

實現

const differenceBy = (a, b, fn) => {
const s = new Set(b.map(fn));
return a.map(fn).filter(el => !s.has(el));
};

測試

differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [2]


分享到:


相關文章: