0
votes
        console.log(previousCompetitors);
        console.log(competitors);
        if(data.isVisible) {
            var moveIndexTo = [];
            for(var q=0; q<competitors.length;q++) {
                moveIndexTo.push(-1);
            }
            for(var i = 0; i<competitors.length; i++) {
                for(var j = 0; j<previousCompetitors.length; j++) {
                    console.log(competitors[i].name);
                    console.log(previousCompetitors[j].name);
                    if(competitors[i].name === previousCompetitors[j].name) {
                        moveIndexTo[j]= i;
                        break;
                    }
                }
            }
            console.log(moveIndexTo);
        }

I'm slowly going insane trying to figure out what is happening here. I have an array of competitor data that updates in order. They are both arrays and I want to track the changes from the previous ordering.

I console.log the data and can see that the data order has been changed yet every single time the moveIndexTo array ends up being [0,1,2,3,4,5] implying that previousCompetitors an Competitors have equal order. How can they be changed between when I console.log them at the top of the code block to when I perform the string comparison?

Competitors and previousCompetitors take roughly the form

[{name:'name1'},{name:'name2'},{name:'name3'},{name:'name4'},{name:'name5'},{name:'name6'}]

with a lot more going on in each object. So If that was previousCompetitors then competitors would be something like

[{name:'name6'},{name:'name2'},{name:'name3'},{name:'name4'},{name:'name5'},{name:'name1'}].

Note the switch of name1 and name6. So I would expect moveIndexTo to be [5,1,2,3,4,0].

1
Can you please edit your question to show a sample input and the corresponding desired output (i.e., example contents of competitors and previousCompetitors, and what moveIndexTo should be afterwards)? - nnnnnn
The data is quite large and nested. But it is simply an array of objects each object has the name field as well as many others. My intention is to use moveIndexTo to record where the object at position j in previousCompetitors currently is in competitors by storing i at the jth index of moveToIndex. - Adam Burke
I pasted your sample data and code into a fiddle, and the result was [5,1,2,3,4,0], just like you expected: jsfiddle.net/1jxmsewr - nnnnnn
Sigh. I don't understand. Thanks for your help. - Adam Burke
Do you have any other code that modifies either array after the above loop? The console will (depending on the browser) have a live link to the actual objects, so if you didn't expand the arrays within the console until after other code updated them you'd see the latest version even though you log them in order. (You can get around this by logging strings: console.log(JSON.stringify(competitors)), etc.) - nnnnnn

1 Answers

2
votes

Just try this : moveIndexTo[i] = j; fiddle at : https://jsfiddle.net/c9mbbpjj/