2009-09-23

Compare Two Arrays

The method below compares two arrays to verify that they are the same.
It is a method, so be sure to place it above or before any code that uses it.
It was written to compare two arrays of
pageRef.marginPreferences.columnsPositions from Adobe InDesign.


Array.prototype.isSameAs = function ( compareTo ) {
//-------------------------------------------------------------------------
//-- I S S A M E A S
//-------------------------------------------------------------------------
//-- Generic: Yes, quite. JavaScript or ExtendScript
//-------------------------------------------------------------------------
//-- Purpose: To compare two arrays to verify that they are the same.
//-------------------------------------------------------------------------
//-- Arguments: The array to compare to. This is a method, it is attached
//-- to the first array.
//-------------------------------------------------------------------------
//-- Calls: Nothing.
//-------------------------------------------------------------------------
//-- Returns: True if the arrays are the same, false otherwise.
//-------------------------------------------------------------------------
//-- Sample Use:
//~ var a1 = [1,2,3] ;
//~ var a2 = [1,2,3] ;
//~ var a3 = [1,2,'3'] ;
//~ var a4 = '[1,2,3]' ;
//~ $.writeln ( a1.isSameAs(a2) ) ;
//~ $.writeln ( a1.isSameAs(a3) ) ;
//~ $.writeln ( a1.isSameAs(a4) ) ;
//-------------------------------------------------------------------------
//-- Notes:
//-- The function expects the elements to exactly match, change
//-- !== to != to allow duck type matches.
//-- This is a method. It must be declared BEFORE / ABOVE any code
//-- that uses it.
//-------------------------------------------------------------------------
//-- Written: 2009.09.22 by Jon S. Winters of electronic publishing support
//-- eps@electronicpublishingsupport.com
//-------------------------------------------------------------------------
//-- Make sure the passed argument is an array.
if ( ! ( ( typeof compareTo == 'object') &&
( compareTo.constructor.toString().match(/array/i) != null ) ) ) {
return false ;
}
//
//-- Make sure the length of both arrays is the same
var masterLength = this.length ;
if ( masterLength != compareTo.length ) {
return false ;
}
//
//-- Now compare every element
for ( var i = masterLength - 1 ; i >= 0 ; i-- ) {
if ( this[i] !== compareTo[i] ) {
return false ;
}
}
//
//-- At this point the arrays must be the same.
return true ;
}

No comments:

Post a Comment