Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find value in an array

Tags:

ruby

People also ask

How do you use Find in array?

JavaScript Array find()The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found. The find() method does not execute the function for empty elements.

How do I find an element in an array of arrays?

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.

How do you get a specific value from an array in JavaScript?

To get only specific values in an array of objects in JavaScript, use the concept of filter().


If you're trying to determine whether a certain value exists inside an array, you can use Array#include?(value):

a = [1,2,3,4,5]
a.include?(3)   # => true
a.include?(9)   # => false

If you mean something else, check the Ruby Array API


Using Array#select will give you an array of elements that meet the criteria. But if you're looking for a way of getting the element out of the array that meets your criteria, Enumerable#detect would be a better way to go:

array = [1,2,3]
found = array.select {|e| e == 3} #=> [3]
found = array.detect {|e| e == 3} #=> 3

Otherwise you'd have to do something awkward like:

found = array.select {|e| e == 3}.first

If you want find one value from the Array, use Array#find:

arr = [1,2,6,4,9] 
arr.find {|e| e % 3 == 0}   #=>  6

If you want to find multiple values from the Array, use Array#select:

arr.select {|e| e % 3 == 0} #=> [ 6, 9 ]
e.include? 6              #=> true

To find if a value exists in an Array you can also use #in? when using ActiveSupport. #in? works for any object that responds to #include?:

arr = [1, 6]
6.in? arr                 #=> true

Like this?

a = [ "a", "b", "c", "d", "e" ]
a[2] +  a[0] + a[1]    #=> "cab"
a[6]                   #=> nil
a[1, 2]                #=> [ "b", "c" ]
a[1..3]                #=> [ "b", "c", "d" ]
a[4..7]                #=> [ "e" ]
a[6..10]               #=> nil
a[-3, 3]               #=> [ "c", "d", "e" ]
# special cases
a[5]                   #=> nil
a[5, 1]                #=> []
a[5..10]               #=> []

or like this?

a = [ "a", "b", "c" ]
a.index("b")   #=> 1
a.index("z")   #=> nil

See the manual.


you can use Array.select or Array.index to do that.