-1

Is that possible to check if the variable array contains exactly the numbers 1,0,0,1?

For example,

var array = [1,0,0,1];
if (array === 1001) alert("success");

4 Answers4

4

You can just join the array to check

The join() method joins all elements of an array (or an array-like object) into a string and returns this string.

Note: You need to use == instead of === because join will return a string.

Like:

var array = [1, 0, 0, 1];
if ( array.join("") == 1001 ) alert("success");

As per suggestion below, you can also use === and compare it with a string.

var array = [1, 0, 0, 1];
if ( array.join("") === "1001" ) alert("success");

Please check more info about join: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

Eddie
  • 26,593
  • 6
  • 36
  • 58
1

Use the join() method to joins all elements of the array into a string and returns this string.

var elements = [1,0,0,1];

console.log(elements.join('') === "1001");
// expected output: true
L Y E S - C H I O U K H
  • 4,765
  • 8
  • 40
  • 57
  • 1
    Just goes to show the "most correct" answer doesn't always get selected on SO. Can't believe the "typecast" answer continues to get upvoted. – Randy Casburn Feb 24 '18 at 16:34
0

Using the method join("") you conver your array into a string with out the commas

Then you use the includes("1001") to check for the expected result

Hope this is what you were looking for. Happy to explain or help in a better solution if needed.

var array = [1,0,0,1];
var string = array.join("");
console.log(string);
if (string.includes('1001')) alert("success");
Gerardo BLANCO
  • 5,590
  • 1
  • 16
  • 35
0

Well, everyone gave a strict answer to your question; but I figured I would add on to it a little. Assuming you want this to be a little more dynamic. This way we check subsets of the array for the string you are looking for, rather than just the entire array.

Array.prototype.containsSequence = function(str, delimiter){
  
  //Determines what is seperating your nums
  delimiter = delimiter || '';
  
  //Check the sub array by splicing it, then joining it
  var checkSection = function (arr, start, end, str){
      return arr.slice(start, end).join(delimiter) === str;
  };
  
  let start = 0; //start of our sub array
  let end = str.length; //the length of the sub array
  
  //Loop through each x size of sub arrays
  while(end < this.length){
    //Check the section, if it is true it contains the string
    if(checkSection(this, start, end, str)){
      return true;
    }
    //Incriment both start and end by 1
    start++;
    end++;
  }
  
  //We dont contain the values
  return false;
};

///Test stuff
const ARRAY = [1,2,3,4,5,6,7,8,9,10];

if(ARRAY.containsSequence('456')){
  console.log('It contains the str');
}else console.log('It does not contain');