Compare 2 arrays ???

JavaScript and client side scripting.

Moderator: General Moderators

Compare 2 arrays ???

Postby Sacapuss » Fri May 20, 2005 4:19 pm

Hi !

Could you let me know how i could, with javascript, detect that 2
arrays contain the same elements, please ?

Thanx for your help !
User avatar
Sacapuss
Forum Commoner
 
Posts: 40
Joined: Mon May 16, 2005 9:46 pm
Location: Earth...

Postby Chris Corbyn » Wed May 25, 2005 11:10 am

Syntax: [ Download ] [ Hide ]
var array1 = new Array(
    'one',
    'two',
    'three'
);

var array2 = new Array(
    'one',
    'two',
    'three'
);

var array3 = new Array(
    'not one',
    'two',
    'not four'
);

function arrayDiffer(arr1, arr2) {
    //Get length of array (and check for equal length)
    l1 = arr1.length;
    l2 = arr2.length;
    if (l1 != l2) {
        return false;
    }
    for (theKey in arr1) { //Check each element in array1 is same as respective element is array2
        if (arr1їtheKey] != arr2їtheKey]) {
           return false;
        }
    }
    return true;
}
User avatar
Chris Corbyn
Breakbeat Nuttzer
 
Posts: 13098
Joined: Wed Mar 24, 2004 8:57 am
Location: Melbourne, Australia

Thanx for your answer, d11wtq !

Postby Sacapuss » Tue May 31, 2005 12:58 am

Thanx for your answer, d11wtq !
User avatar
Sacapuss
Forum Commoner
 
Posts: 40
Joined: Mon May 16, 2005 9:46 pm
Location: Earth...

Postby thedamo » Fri Jul 15, 2005 7:37 pm

maybe I have not understood the question, but could you just use the array_diff() function to if it returns a 0 length array, you then know that they are the same.

e.g.

Syntax: [ Download ] [ Hide ]
$myArray = array_diff($array1, $array2);
if(count($myArray) < 1)
print(&quote;arrays are the same&quote;);
thedamo
Forum Newbie
 
Posts: 9
Joined: Fri Jul 15, 2005 7:23 am
Location: Sydney Australia

Postby Burrito » Fri Jul 15, 2005 7:49 pm

this was for JS, not php...
User avatar
Burrito
Spockulator
 
Posts: 4712
Joined: Wed Feb 04, 2004 9:15 pm
Location: Eden, Utah


Return to Javascript

Who is online

Users browsing this forum: No registered users and 5 guests