I have an array of objects and I want to find which element in the array has a particular attribute equal to a value, specifically which element in this array has an object that has :parent_id
equal to 55
.
How can I do this?
To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.
Ruby | Array class find_index() operation Array#find_index() : find_index() is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.
indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
To find the index:
array.index{ |item| item.parent_id == 55 }
To find the item:
array.find{ |item| item.parent_id == 55 }
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