Algorithms, Blockchain and Cloud

How to Test Element in Array (In Array) and Array Contains in Javascript?


The Javascript has the includes function that can be used to test if a given array or string contains an element or character. For example:

["a", "b", "c"].includes("a");
true
["a", "b", "c"].includes("aa");
false
"abc".includes("a")
true
"abc".includes("aa")
false

For Array-type object, you can define the includes function like this (by extending its prototype of Array):

if (!Array.prototype.includes) {
  Array.prototype.includes = function(key) {
    for (var i = this.length; i--; ) {
      if (key === this[i]) {
        return true;
      }
    }
    return false;
  }
}

For String-type values, it is simply the alias of indexOf funcntion in Javascript:

if (!String.prototype.includes) {
  String.prototype.includes = function(key) {
    return this.indexOf(key) != -1;
  }
}

We can also extend the prototype chain of String object:

String.prototype.InArray = function(arr) {
  for (var i = arr.length; i --; ) {
    // typeof this = object
    // type of arr[i] = string
    if (arr[i] === String(this)) {
      return true;
    }
  }
  return false;
}

So we can use it this way:

"1".InArray([0, 1])
false
"1".InArray([0, "1"])
true

It is strange that typeof this equals to “object” instead of “string” and that is why we need to convert it to string via String() constructor/function. Alternatively, you can use double equals == to ignore the types when doing comparison, instead of triple equals === (strict comparisons).

Looping backwards gives more advantages i.e. no need to declare an extra variable length, and might be implemented a bit faster. In ES6, you might also use the for .. of syntax sugar to loop through array of values, like this:

var arr = [1, 2, 3];
for (var x of arr) {
  console.log(x);
}

–EOF (The Ultimate Computing & Technology Blog) —

NodeJs / Javascript

411 words
Last Post: How to Use Keyboard Arrow Keys for WordPress Posts Navigation?
Next Post: How to Enable Inline Chrome Extension Installation in Chrome Browser?

The Permanent URL is: How to Test Element in Array (In Array) and Array Contains in Javascript? (AMP Version)

Exit mobile version