crooksy88
crooksy88

Reputation: 3851

AS3 Compare 2 arrays for any difference

Hopefully someone can shed some light on this 'seemingly' straight forward issue. I need to compare two arrays to see if they are identical.

var _array1:Array = new Array();
var _array2:Array = new Array();


_array1.push(1,2,3,4,5);

_array2 = _array1.concat();

trace("_array2 "+_array2);
//traces 1,2,3,4,5 so I am assuming the copy took place.


if (_array2 == _array1) {
    trace("the same");
} else {
    trace("different");
}

This test traces 'different' even though the arrays are seemingly the same.

Would anyone know where I'm going wrong?

Thanks,

Mark

Upvotes: 0

Views: 5452

Answers (2)

PatrickS
PatrickS

Reputation: 9572

Arrays are containers, so checking for equality would be equivalent to checking equality of the elements they contain as well as these elements' indexes.

Without going to deep into Object comparisons, your example doesn't work because these arrays are two different unrelated Objects. You could add or remove elements from one without affecting the other.

If you want to compare the elements that each Array contains, you may have to come up with a different method, recursively comparing each element , which may not be a simple issue when dealing with complex Objects, but pretty straighforward for integers, Numbers or Strings

Upvotes: 0

Jevgenij Dmitrijev
Jevgenij Dmitrijev

Reputation: 2238

If you want to compare arrays just use small trick:

if (String (_array2 ) == String ( _array1) )
{
    trace("the same");
} else {
    trace("different");
}

Upvotes: 10

Related Questions