easwee
easwee

Reputation: 15895

Unexplained array sort occuring in loop

I'm working on a practice project - a Dota related mini game.

http://jsfiddle.net/easwee/MwGsd/

You are making combinations of 3 reagents to summon(invoke) a spell.

I have an array containing all possible spell combinations and another empty array which records keypresses and stores the pressed reagent in that array. You always need 3 reagents to create a spell - the order of reagents does not matter.

So far all works, but I'm encoutering a problem once I start comparing the inputed reagents array to the spell list array:

I'm using the following compare function:

function compareArrays(arr1, arr2) {
    return arr1.sort().toString() === arr2.toString()
}

I sort the array and compare in the following function (reagentStack - contains the inputed reagents):

    function updateSpellList(reagentStack){         
        for( var spell in spellList ) {
            var compareStack = reagentStack;
                compareSpell = spellList[spell];

            console.log(spell);
            console.log('compareStack: ' + compareStack + ' / compareSpell: ' + compareSpell + ' / reagentStack: ' + reagentStack); // check this log in fiddle console
            console.log('---');

            if(compareArrays(compareStack, compareSpell)) {
                invokedSpell = spell;                   
                console.log('Invoked spell: ' + invokedSpell);
                break;
            }

        }           
    }

In the example fiddle (here) if you press Q + Q + E + R you create a spell combination (in this case icewall).

It is comparing all ok and follows my script logic (set's compareStack to reagentStack, sorts the compareStack and compareSpell arrays and compares), but I can't understand why does it also sort reagentStack array since I'm not sorting it anywhere in the whole script?

It is not sorted on the first iteration of for loop, but get's sorted on second iteration and won't compare anymore correctly since now compareStack is getting set to a sorted reagentStack instead to the originally inputed.

Console log:

coldsnap
compareStack: quas,quas,exort / compareSpell: quas,quas,quas / reagentStack: quas,quas,exort
---
ghostwalk
compareStack: exort,quas,quas / compareSpell: quas,quas,wex / reagentStack: exort,quas,quas

On first loop the reagentStack is not sorted on second loop it is already sorted - why?

Upvotes: 1

Views: 43

Answers (1)

Sirko
Sirko

Reputation: 74036

You do sort the array in question: On this line you create a reference to the very array:

var compareStack = reagentStack;

which gets then passed on to

if(compareArrays(compareStack, compareSpell)) {

where it is sorted in turn. sort() modifies the array it is applied to unlike some other operations, which just return a new modified array.

If you want a (shallow) copy of the array, use slice():

var compareStack = reagentStack.slice(0);

Example fiddle

Upvotes: 4

Related Questions