Skip to content
Fix Code Error

Check if an element is present in an array

March 13, 2021 by Code Error
Posted By: Anonymous

The function I am using now to check this is the following:

function inArray(needle,haystack)
{
    var count=haystack.length;
    for(var i=0;i<count;i++)
    {
        if(haystack[i]===needle){return true;}
    }
    return false;
}

It works. What I’m looking for is whether there is a better way of doing this.

Solution

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);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array at which to begin searching)

As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.

Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

Answered By: Anonymous

Related Articles

  • How do I include certain conditions in SQL Count
  • What are the new features in C++17?
  • Create new dataframe column with numbered time windows
  • JavaScript equivalent of PHP's in_array()
  • ng if with angular for string contains
  • Is there a quick way for checking whether a date…
  • How to properly do JSON API GET requests and assign…
  • Convert Daily Data into Weekly Data and summarize…
  • R: How can I create rows based on the values of other rows?
  • Multiple separate IF conditions in SQL Server
  • Dodged bar plot in R based on to columns with count…
  • R- Calculate rolling mean from values match a column…
  • Pandas resample monthly data into custom frequency…
  • Deprecation warning in Moment.js - Not in a…
  • For-each over an array in JavaScript
  • Re-arrange position in a table maitaining order
  • How does PHP 'foreach' actually work?
  • How to use html template with vue.js
  • Using an array as needles in strpos
  • Octave using 'for' statement to show two animations…
  • How to get substring of NSString?
  • Is it possible to apply CSS to half of a character?
  • Failed to configure a DataSource: 'url' attribute is…
  • How to get nested JSON data in vue.js
  • How to filter a RecyclerView with a SearchView
  • What is an IndexOutOfRangeException /…
  • Undefined reference to 'vtable for ✘✘✘'
  • Javascript filtering a nested array to exclude…
  • What's the best way to get the last element of an…
  • startsWith() and endsWith() functions in PHP
  • Show/hide 'div' using JavaScript
  • JS jQuery - check if value is in array
  • How to create a box plot for a grouped data
  • jQuery.inArray(), how to use it right?
  • Peak signal detection in realtime timeseries data
  • How to show title in hover - css / jquery
  • How do I keep only the first map and when the game…
  • Determine whether an array contains a value
  • Smart way to truncate long strings
  • Best way to extract messy HTML tables using BeautifulSoup
  • Ukkonen's suffix tree algorithm in plain English
  • in_array multiple values
  • How is the complexity of algorithm to find…
  • COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?
  • How would you count occurrences of a string…
  • Get value using key
  • How can I check if a string contains a character in C#?
  • For loop for HTMLCollection elements
  • ternary operator usage within v-bind class
  • AWS CLI S3 A client error (403) occurred when…
  • VUE Error when run test unit
  • How can I access and process nested objects, arrays or JSON?
  • Use of Jquery on scroll event
  • C++ Need help sorting a 2D string array
  • Pandas conditional counting by date
  • How to replace item in array?
  • Dynamically update values of a chartjs chart
  • How do I use shell variables in an awk script?
  • easiest way to extract Oracle form xml format data
  • Pandas group-by and sum
  • How do I use arrays in C++?
  • Python dataframe converting time date 'SylmiSeb'…
  • What are the undocumented features and limitations…
  • Fastest way to iterate over all the chars in a String
  • Maximum XOR With an Element From Array | Leetcode
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • in_array() and multidimensional array
  • How to change the datetime format in pandas
  • Find the nth occurrence of substring in a string
  • How to check for interval overlap for grouped item…
  • Implementing two interfaces in a class with same…
  • MySQL query String contains
  • How to compare arrays in JavaScript?
  • Why my "title" bloc doesn't go to bottom?
  • Conditional aggregation based on groups in a data frame R
  • Oracle: If Table Exists
  • Adobe XD to responsive html
  • Update backbone model on change of global variable?
  • Simplest way to create Unix-like continuous pipeline…
  • Knight's tour Problem - storing the valid moves then…
  • How would I be able to multiple select and pass data…
  • Replace given value in vector
  • mongodb group values by multiple fields
  • Using React-Three-Fiber
  • moment: Array.prototype.some called on null or undefined
  • What is the cause of [Vue warn]: Invalid prop:…
  • How to block form submissions if the message field…
  • Add new reactive column in Shiny
  • Having trouble with my nav bar/header, It used to…
  • Why does C++ code for testing the Collatz conjecture…
  • dynamically add and remove view to viewpager
  • jQuery Mobile: document ready vs. page events
  • How to check if a string "StartsWith" another string?
  • Questions every good PHP Developer should be able to answer
  • Apache server keeps crashing, "caught SIGTERM,…
  • JS search in object values
  • Javascript - remove an array item by value
  • What is a NullReferenceException, and how do I fix it?
  • Does my application "contain encryption"?
  • Jquery, checking if a value exists in array or not

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Correct format specifier for double in printf

Next Post:

Remove stubborn underline from link

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error