Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if an array of objects includes an attribute with a specific value

Tags:

The following code works, but can you tell me if this is the right way to do it?

I have an array of Position objects and I want to check if it contains an object which attribute 'hidden' has "false' value:

<% if positions.collect{|position| position.hidden}.include?(false) %>
  ...
<% end %>
like image 288
Martin Petrov Avatar asked Mar 19 '11 05:03

Martin Petrov


People also ask

How do you check if an array contains a specific value?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check if an array of objects contains a value in react?

To check if an element exists in an array in React: Use the includes() method to check if a primitive exists in an array. Use the some() method to check if an object exists in an array.

How do you find a specific object in an array of objects?

To search a particular object, we will use the Array prototype find method. This returns a value on a given criterion, otherwise, it returns 'undefined'. It takes two parameters, one required callback function and an optional object, which will be set as a value of this inside the callback function.


1 Answers

<% if positions.any?{|position| !position.hidden} %>
  ...
<% end %>

Using the any? method

like image 197
Mike Lewis Avatar answered Oct 10 '22 20:10

Mike Lewis