HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Check if a JavaScript array has only one or many matches

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
onejavascripthascheckmatchesmanyonlyarray

Problem

Finding values in an array that match a given condition is one of the most common tasks when it comes to working with arrays. Luckily, JavaScript's Array methods never cease to be of help, allowing to easily perform such operations.
Using Array.prototype.filter() and Array.prototype.length, you can easily check if an array has only one value matching the given function.
To find the index of the only matching element, you can use Array.prototype.findIndex().
In order to check if an array has more than one value matching the given function, you can use the same approach. The only difference is that you need to change the comparison operator from === to >.
Finding the indexes of all matching elements is a little more involved. You need to use Array.prototype.reduce() to loop over elements and store the indexes of matching elements.

Solution

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

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


To find the index of the only matching element, you can use Array.prototype.findIndex().
In order to check if an array has more than one value matching the given function, you can use the same approach. The only difference is that you need to change the comparison operator from === to >.
Finding the indexes of all matching elements is a little more involved. You need to use Array.prototype.reduce() to loop over elements and store the indexes of matching elements.

Code Snippets

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

hasOne([1, 2], x => x % 2); // true
hasOne([1, 3], x => x % 2); // false
const findIndex = (arr, fn) => arr.findIndex(fn);

findIndex([1, 2, 3, 4], x => x % 2); // 0
findIndex([2, 4, 6, 8], x => x % 2); // -1
const hasMany = (arr, fn) => arr.filter(fn).length > 1;

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

Context

From 30-seconds-of-code: array-has-only-one-match-or-many

Revisions (0)

No revisions yet.