Javascript: How to check if array of object has one and only one item with given value?

Viewed 6129

I know that in Javascript I can use .some or .every on arrays to check if they have atleast one item or every item that passes the test implemented by the provided function.

Here is some examples:

[2, 5, 8, 1, 4].some(x => x > 10);  // false
[12, 5, 8, 1, 4].some(x => x > 10); // true

[12, 5, 8, 130, 44].every(x => x >= 10); // false
[12, 54, 18, 130, 44].every(x => x >= 10); // true

I'm looking for checking if an array has "one and only one" item that passes the given function. I would like to have some method like the following:

[12, 5, 12, 13, 4].oneAndOnlyOne(x => x >= 10); // false
[2, 11, 6, 1, 4].oneAndOnlyOne(x => x >= 10); // true

Do you know any new ECMA Script 6 way or any easy/quick way, even using lodash, to check if in array there is one and one only occurrence of item that has certain values?

5 Answers
Related