Check if an array contains object

The easiest way to check if an array of objects contains a specific one in pure JavaScript.


Libraries

Code Snippet
// For modern browsers it's recommend to use
function ArrayContains(yourArray, obj) {
    return yourArray.indexOf(obj) !== -1;
}


// For older browsers
function ArrayContains(yourArray, obj) {
    var i = yourArray.length;
    while (i--) {
       if (yourArray[i] === obj) {
           return true;
       }
    }
    return false;
}


Implementation

The usage is super easy. Here is a little example: <code> myArray = ["a", "b", "c"]; var containsA = ArrayContains(myArray, "a"); // The variable has the value true! var containsE = ArrayContains(myArray, "e"); // The variable has the value false! </code> Optionally you can extend the array with <code> Array.prototype.contains = function(obj) { ArrayContains(this, obj); } </code> Then you have the abillity to call somehting like <code> myArray = ["a", "b", "c"]; var containsA = myArray.contains("a"); // The variable has the value true! var containsE = myArray.contains("e"); // The variable has the value false! </code> what makes everything a bit easier!





Comments
  • mode_editWrite a comment



  • forumComments




Embed Code

We provide special containers which include the full snippet and a link to this site. So for example when you make a tutorial and you are using code from this site, you can use one of the following snippet embeddings:

Load Preview Get Code Close Preview







    Share
    Rating
    thumb_up 1 thumb_down
    Author
    Thorolus

    I'm the head developer and co-founder of GlovilGames Studios (glovilgames.com) and other platforms GlovilGames created, like vsnippets.com, worth-calculator.net, python-obfuscator.com and some mobile apps and games.

    Tags
    Array
    contains



    Informations

    posted on 2016-09-14 13:21:00

    viewed 197 times

    snippet's UUID is 57d9329bf26f8

    Similar Snippets