Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: compare arrays

  1. #1
    New Coder
    Join Date
    Aug 2009
    Posts
    84
    Thanks
    10
    Thanked 0 Times in 0 Posts

    compare arrays

    hi i have two arrays and i need to know which strings are in both arrays.

    i know how to do the bit if the string is in both but i don't know how to compare them as such.

    thanks

  • #2
    Regular Coder
    Join Date
    Mar 2006
    Posts
    726
    Thanks
    35
    Thanked 132 Times in 123 Posts
    Most modern browsers extend Arrays with some common useful methods-
    filter(function) returns an array containing the members that pass a test or condition,
    and indexOf(value) returns the first element that matches its argument, or -1, if no instance is found.

    To extend support for these to IE and other older clients you can
    add them if they are not defined.


    Code:
    if(![].filter){
    	Array.prototype.filter= function(fun, scope){
    		var L= this.length, A= [], i= 0, val;
    		if(typeof fun== 'function'){
    			while(i< L){
    				if(i in this){
    					val= this[i];
    					if(fun.call(scope, val, i, this)){
    						A[A.length]= val;
    					}
    				}
    				++i;
    			}
    		}
    		return A;
    	}
    }
    if(![].indexOf){
    	Array.prototype.indexOf= function(what, i){
    		i= i || 0;
    		var L= this.length;
    		while(i< L){
    			if(this[i]=== what) return i;
    			++i;
    		}
    		return -1;
    	}
    }
    var arr1= [1, 2, 3, 4, 5, 6, 7, 8, 9],
    arr2= [2, 4, 6, 8, 10, 12, 14, 16, 18];

    var shared=arr1.filter(function(itm){
    return arr2.indexOf(itm)!= -1
    });


    alert('shared='+shared)


    /* returned value: (String)
    shared=2,4,6,8



    If you need to repeatedly compare arrays you can add your own method-

    Code:
    Array.prototype.common= function(ar){
    	return this.filter(function(itm){
    		return ar.indexOf(itm)!= -1;
    	});
    }
    var shared=arr1.common(arr2);
    */
    Last edited by mrhoo; 06-12-2010 at 05:03 PM. Reason: grammar

  • #3
    New Coder
    Join Date
    Aug 2009
    Posts
    84
    Thanks
    10
    Thanked 0 Times in 0 Posts
    ok great thanks


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •