Link to home
Start Free TrialLog in
Avatar of cursive
cursive

asked on

array.sort() being ignored in a for... in loop

I have an array whihc I have put a sort on, when I sue a for in loop to loop through the array, it acts as if the array hadn't been sorted. I noticed that using a regular for loop solves this problem, however, however I need this to work with the for in loop. I am aware that a for in will go through an array in reverse order, however this isn't the issue.

Here is the code greatly simplified code, and below, the results of the traces

Many thanks for helping solve this problem

function layout() {
      var cats = ["40artist", "30still", "50fashion"];
      trace("---- Part 1: "+cats);
      cats.sort();
      trace("---- Part 2: "+cats+"\n");
      for (var i in cats) {
            trace("---- Part 3: "+cats[i]);
      }
      trace("\n---- Part 4: "+cats+"\n");
}

layout();


---- Part 1: 40artist,30still,50fashion
---- Part 2: 30still,40artist,50fashion

---- Part 3: 40artist
---- Part 3: 30still
---- Part 3: 50fashion

---- Part 4: 30still,40artist,50fashion

Avatar of Ashish Patel
Ashish Patel
Flag of India image

Try changing, though your code seems working for me.
cats.sort();
to
cats = cats.sort();
Avatar of Aneesh Chopra
cats.sort() is working fine in your code,
problem is that you are tracing the part3 using "for in" loop which does not gets effected with Array.sort();
you should use "for()" loop

here is the fixed code and it works fine:

function layout()
{
	var cats = ["40artist", "30still", "50fashion"];
	trace("---- Part 1: "+cats);
	cats.sort();
	trace("---- Part 2: "+cats+"\n");
	for (var i = 0; i<cats.length; i++)
	{
		trace("---- Part 3: "+cats[i]);
	}
	trace("\n---- Part 4: "+cats+"\n");
}
 
layout();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Aneesh Chopra
Aneesh Chopra
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial