30秒学会 JavaScript 片段 · 2023年7月24日

30秒学会 JavaScript 片段 – Check if array has only one match

Checks if an array has only one value matching the given function.

  • Use Array.prototype.filter() in combination with fn to find all matching array elements.
  • Use Array.prototype.length to check if only one element matches fn.

代码实现

const hasOne = (arr, fn) => arr.filter(fn).length === 1;

hasOne([1, 2], x => x % 2); // true
hasOne([1, 3], x => x % 2); // false

翻译自:https://www.30secondsofcode.org/js/s/array-has-only-one-match