Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 616
smartmouse Avatar asked Jul 12 '17 08:07

smartmouse


People also ask

How do you check if an array of objects includes a value?

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 .

How do you check if an array of objects has a value in JavaScript?

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.

How do you check if an object has a specific value in JavaScript?

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 .


1 Answers

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]));
like image 58
kind user Avatar answered Oct 04 '22 23:10

kind user