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?
Checking if Array of Objects Includes Object We can use the some() method to search by object's contents. The some() method takes one argument accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .
Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.
JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty() method. Use the in operator. Compare property with undefined .
You could reach desired result using Array#filter
.
const oneAndOnlyOne = arr => arr.filter(v => v >= 10).length == 1;
console.log(oneAndOnlyOne([12, 5, 12, 13, 4]));
console.log(oneAndOnlyOne([2, 11, 6, 1, 4]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With