How to check if an element is in an array

check if value already exists in array javascript
javascript check if value exists in array of objects
check if array contains value java
javascript array contains object
remove element from array javascript
javascript array contains string
typescript array includes
check if value already exists in array jquery

In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for contain, include, or has, and a quick search through the book turned up nothing. Any idea how to check for this? I know that there is a method find that returns the index number, but is there a method that returns a boolean like ruby's #include??

Example of what I need:

var elements = [1,2,3,4,5]
if elements.contains(5) {
  //do something
}

Check if an element is present in an array, ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method. [1, 2, 3].includes(2);  Check whether an array of strings can correspond to a particular number X; Check if all elements of the given array can be made 0 by decrementing value in pairs; Check if URL is valid or not in Java; Check if the array has an element which is equal to product of remaining elements; Check if elements of an array can be arranged in a Circle with consecutive difference as 1; Check if a File is hidden in Java

For those who came here looking for a find and remove an object from an array:

Swift 1

if let index = find(itemList, item) {
    itemList.removeAtIndex(index)
}

Swift 2

if let index = itemList.indexOf(item) {
    itemList.removeAtIndex(index)
}

Swift 3, 4, 5

if let index = itemList.index(of: item) {
    itemList.remove(at: index)
}

How do I check if an array includes a value in JavaScript?, That means that you can detect if an array includes a NaN : The nice thing about it is that the iteration is aborted once the element is found so unnecessary  Here we traverse the array from index 0 to array.length - 1 index, notice only less than operator (<) instead of less than equal to (<=). Now in the if condition, we simply check if array element is equal to element to be searched value's. If it is, print element found. Let's define for conditions.

Use this extension:

extension Array {
    func contains<T where T : Equatable>(obj: T) -> Bool {
        return self.filter({$0 as? T == obj}).count > 0
    }
}

Use as:

array.contains(1)

Updated for Swift 2/3

Note that as of Swift 3 (or even 2), the extension is no longer necessary as the global contains function has been made into a pair of extension method on Array, which allow you to do either of:

let a = [ 1, 2, 3, 4 ]

a.contains(2)           // => true, only usable if Element : Equatable

a.contains { $0 < 1 }   // => false

How to Check If a Value Exists in an Array in JavaScript, You can use the indexOf() method to check whether a given value or element exists in an array or not. The indexOf() method returns the index of the element  C Program to Search an Element in an Array. This program asks the user to enter the Array size, Array elements, and the Search item value. Next, this C Program to Search an Element in an Array will check whether the user entered search item is present in the array or not using For Loop.

If you are checking if an instance of a custom class or struct is contained in an array, you'll need to implement the Equatable protocol before you can use .contains(myObject).

For example:

struct Cup: Equatable {
    let filled:Bool
}

static func ==(lhs:Cup, rhs:Cup) -> Bool { // Implement Equatable
    return lhs.filled == rhs.filled
}

then you can do:

cupArray.contains(myCup)

Tip: The == override should be at the global level, not within your class/struct

Check if a value is present in an Array in Java, Given an array, the task is to check whether a certain element is present in this Array or not, in Java. Examples: Input: arr[] = [5, 1, 1, 9, 7, 2, 6, 10], key = 7 Output:​  In this program, you'll learn to check if an array contains a given value in Java. When you run the program, the output will be: In the above program, we have an array of integers stored in variable num. Likewise, the number to be found is stored in toFind. Now, we use a foreach loop to iterate through all elements of num and check individually

I used filter.

let results = elements.filter { el in el == 5 }
if results.count > 0 {
    // any matching items are in results
} else {
    // not found
}

If you want, you can compress that to

if elements.filter({ el in el == 5 }).count > 0 {
}

Hope that helps.


Update for Swift 2

Hurray for default implementations!

if elements.contains(5) {
    // any matching items are in results
} else {
    // not found
}

Array.prototype.includes(), The includes() method determines whether an array includes a sameValueZero algorithm to determine whether the given element is found. Like, I want to create an array with a list of printer names. These will be fed to a method, which will look at each string in turn, and if the string is the same as a value in an array, do that action. These are the names of the printers, they are being fed to the PrinterSetup method.

Check if value exists in Array - jQuery and JavaScript, Execute script when the Array contains the particular value. etc. If you are familiar with PHP, where you can use the in_array() function to search  This solution is more robust. You can now check whether any number satisfying a certain condition is in your array nums. For example, check whether any number that is greater than or equal to 5 exists in nums: (len(filter (lambda x : x >= 5, nums)) > 0)

in_array - Manual, Loose checking returns some crazy, counter-intuitive results when used with certain arrays. Checks if an element is found in an array or one of its subarray. Step by step descriptive logic to search element in array using linear search algorithm. Input size and elements in array from user. Store it in some variable say size and arr. Input number to search from user in some variable say toSearch. Define a flag variable as found = 0.

How to Check if an Array Contains a Value in Java Efficiently?, binarySearch() : binarySearch() can ONLY be used on sorted arrays. If the array is sorted, you can use the following code to search the target element:  Simply pass the value to search for and the array to the function and it will tell you whether the string exists as a part of an array value or not.

Comments
  • if find(elements, 5) != nil { } is not good enough?
  • I was hoping for something even cleaner, but its not looking good. I haven't found anything in the documentation or the book yet.
  • Any documentation about this kind of global functions?
  • Is this supposed to work if each item inside the array (and the item we are searching for) is of type Dictionary<String, AnyObject>? Trying to achieve that but I get compile-time error.
  • @ppalancica: This requires that the array elements conform to the Equatable protocol (which Dictionary<String, AnyObject> doesn't). There is a second variant of contains() which takes a predicate (compare stackoverflow.com/questions/29679486/…) perhaps you can use that, e.g. if contains(array, { $0 == dict } ) ...
  • How to search specific element from generic array? say [AnyObject] ?
  • Please answer relevant to the question. This question just asks about finding a element in array, not remove or update it. You can raise a separate question and answer it yourself also.
  • find is faster.
  • depending on what you're used to though, .contains may feel more intuitive and memorable
  • Could you explain your syntax by breaking it down? I've never seen this formatting before and you've got a lot of advanced stuff happening at once!
  • I like the filter solution because you can use it for all sorts of things. For instance, I was porting some code that looped and looped trying to see if a list already had an item with one of it's fields containing a string value. It's one line in Swift, using a filter on that field.
  • filter is inefficient because it always loops over all elements instead of returning immediately when the element is found. Better use find() instead.