0

I have these cat breeds

cats = [
'Abyssinian',
'Balinese',
'Bombay',
'Birman'];

Now the code written is generally something like this

 for(var i in cats)
 {
  ... do
 }

Now I have to modify the same function in javascript. I can only modify to see if i is any of Balinese or Bombay .. then do these

I am thinking

 for(var i in cats)
 {
  if(i == 'Balinese' || i == 'Bombay'){
  ... do
  }
 }

Instead I would like something like i contains Balinese,Bombay instead of writing the | clause in middle?

 for(var i in cats)
 {
  if(i.contains('Balinese', 'Bombay'){   //this would be better, suggestions?
  ... do
  }
 }

How?

CD..
  • 72,281
  • 25
  • 154
  • 163
Some Java Guy
  • 4,992
  • 19
  • 71
  • 108

5 Answers5

1

Try this code,

This adds the .indexOf() in non-supported browsers

if (!Array.prototype.indexOf) {  
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {  
        "use strict";  
        if (this == null) {  
            throw new TypeError();  
        }  
        var t = Object(this);  
        var len = t.length >>> 0;  
        if (len === 0) {  
            return -1;  
        }  
        var n = 0;  
        if (arguments.length > 0) {  
            n = Number(arguments[1]);  
            if (n != n) { // shortcut for verifying if it's NaN  
                n = 0;  
            } else if (n != 0 && n != Infinity && n != -Infinity) {  
                n = (n > 0 || -1) * Math.floor(Math.abs(n));  
            }  
        }  
        if (n >= len) {  
            return -1;  
        }  
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);  
        for (; k < len; k++) {  
            if (k in t && t[k] === searchElement) {  
                return k;  
            }  
        }  
        return -1;  
    }  
} 

Adding contains method in Array prototype

 Array.prototype.contains = function(){ 
       for(var i=0,len=arguments.length;i<len;i++){
          if(this.indexOf(arguments[i]) !== -1){ 
              return true;
          } 
       }
       return false;
    }

Now, you can use like this,

var cats = [
'Abyssinian',
'Balinese',
'Bombay',
'Birman'];

if(cats.contains('Balinese')){
  console.log('Balinese');
}

if(cats.contains('Balinese','Bombay')){
  console.log('Balinese,Bombay');
}

if(cats.contains('lines','Bombay')){
  console.log('lines,Bombay');
}

if(cats.contains('lines','mbay')){
  console.log('lines,mbay');
}

If you are using jQuery, this code can be made simpler :)

Jashwant
  • 28,410
  • 16
  • 70
  • 105
0

Try nested loops?

var cats = ["Abyssinian", "Balinese", "Bombay", "Birman"];
var thisAndThat = ["Abyssinian", "Apple", "Siberian", "Windows", "StackOverflow"];

for(var i in cats) {
    for(var x in thisAndThat) {
        if(cats[i] == thisAndThat[x]){
            ... do
        }
    }
}

With jQuery

$.each(thisAndThat, function(key, value){
  if( $.inArray(value, cats) > -1 ){
    alert(value+" is inside the cats array.");
  }
});
DACrosby
  • 11,116
  • 3
  • 39
  • 51
0

check this code,

var cats=['Abyssinian', 'Balinese', 'Bombay', 'Birman'];

Array.prototype.contains=function(incattype){

    for(var i=0; i<cats.length;i++){

        if(cats[i]==incattype) {
            return true;
        } else{
             return false;
        }      
    }
};


  var catslist=['Abyssinian', 'Balinese', 'Bombay11' ];

    for(var i=0; i<catslist.length;i++){

        document.write(cats.contains(catslist[i]));
    }        

link;-

http://jsfiddle.net/fPdej/2/

sandeep patel
  • 436
  • 4
  • 16
  • why build a contains method, when there already is an [`indexOf`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf)-method? – Yoshi Jun 27 '12 at 08:25
0

First off, its important to realise that if you are traversing a javascript array with for...in then it is imperative that you use the hasOwnProperty method:

for(var i in cats){
    if(cats.hasOwnProperty(i))
        console.log(cats[i]);        
}

You really should be using for(;;) like so:

for(var i=0;i<cats.length;i++){
   console.log(cats[i]);
}

All that aside, you are looking for Array.indexOf, which is supported by modern browser but may have less support in older browsers - this is why most frameworks (jQuery, Moo, prototype etc) define their own variant of this method (See this question's answers for more detail).

var cats = ["Abyssinian","Balinese","Bombay","Birman"];

var test = ["Abyssinian","Balinese"];

for(var i in cats){
    if(cats.hasOwnProperty(i) && test.indexOf(cats[i]) != -1)
        console.log(cats[i]);        
}

Live example: http://jsfiddle.net/4xJsg/

Community
  • 1
  • 1
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

It's not recomended to use for-in loops, because they are up to seven times slower than for, while or do-while ones. Instead of for-in, you can use for-each, too, which is not as faster as for or while but is more similar to for-in loops.

Combining it with regular expressions, my approach is:

var cats = [
    'Abyssinian',
    'Balinese',
    'Bombay',
    'Birman'
];

cats.forEach(function(cat, index){
    if(cat.match(/Abyssinian|Birman/)){
    // Do what you want
    }
});
sgmonda
  • 2,615
  • 1
  • 19
  • 29