30秒学会 JavaScript 片段 · 2023年8月2日

30秒学会 JavaScript 片段 – Remove matching elements from array

Mutates an array by removing elements for which the given function returns false.

  • Use Array.prototype.filter() to find array elements that return truthy values.
  • Use Array.prototype.reduce() to remove elements using Array.prototype.splice().
  • The callback function is invoked with three arguments (value, index, array).

代码实现

const remove = (arr, func) =>
  Array.isArray(arr)
    ? arr.filter(func).reduce((acc, val) => {
      arr.splice(arr.indexOf(val), 1);
      return acc.concat(val);
    }, [])
    : [];

remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]

翻译自:https://www.30secondsofcode.org/js/s/remove-matching-array-elements