Is there a way to compare two array using mootools?

General Discussion about Mootools 1.2

Moderator: 1.2 Moderators

Is there a way to compare two array using mootools?

Postby Pingoochan on Tue Aug 18, 2009 4:43 pm

Hi,

i'm trying to compare two array containing users id's in order to retrieve the newest ones.
Is there a way to do it using mootools?

Thanks a lot!
Pingoochan
 
Posts: 6
Joined: Fri Jun 26, 2009 10:41 am

Re: Is there a way to compare two array using mootools?

Postby adamnfish on Thu Sep 03, 2009 9:53 pm

Mootools doesn't have a built in method to do this but it's easy enough to write your own!

Be advised that for very large arrays this might be quite slow. In JavaScript, unless array1 is *the same array* (rather than just an array containing the same information) as array2 it will be 'different' so:


is always false, whereas
  1. var a = [1, 2, 3]
  2. a == a

will be true. If we're talking about a very large list of user ids, then we're going to have to run through every entry in the arrays and compare them!

We can add a method to the Array prototype thus:

  1. Array.implement({
  2.     equalTo: function(arr){
  3.         if(this.length !== arr.length){
  4.             return false;
  5.         }
  6.         for(var i = this.length - 1; i >= 0; i--){
  7.             if(this[i] !== arr[i]){
  8.                 return false;
  9.             }
  10.         }
  11.         return true;
  12.     }
  13. });

this first establishes that the arrays are the same length (it's a very quick false if they aren't!) and then runs backwards through the arrays checking each entry. I decided to make it go backwards because I figure you (and anyone else who uses this) are more likely to add something to the end than the begining so it might find the change more quickly? Just invert the for loop if you don't agree!

It can be used thus:
  1. [1, 2, 3].equalTo([1, 2, 4, 3]) // false
  2. [1, 2, 3].equalTo([1, 2, 3]) // true
  3. [].equalTo([]) // true

or with appropriate variable, more generally:
  1. a.equalTo(b) // for a and b arrays


Hope that helps, good luck
User avatar
adamnfish
mootools connoisseurs
 
Posts: 27
Joined: Fri Aug 08, 2008 2:26 am
Location: London, UK


Return to General

Who is online

Users browsing this forum: No registered users and 1 guest