AS 3による複雑なオブジェクトの並べ替え規則[DEMO]


ソース:
package
{
	import flash.display.Sprite;
	
	/**
	 *   
	 * @author Jave.Lin(afeng)
	 **/
	public class TestComplexSort extends Sprite
	{
		public function TestComplexSort()
		{
			super();
			
			var lastNameArr:Vector.<String>=new Vector.<String>();
			lastNameArr.push("Lin","Smith","Steven","Abros","BB","CCC","D","EE","FF","GG","Gates","HH");
			
			var firstNameArr:Vector.<String>=new Vector.<String>();
			firstNameArr.push("Jave","John","Harry","Waston","Bill","Tom","Jerry");
			
			var ageMax:uint=150;
			
			var personArr:Vector.<Person>=new Vector.<Person>();
			
			for (var i:int = 0; i < 10; i++) 
			{
				var p:Person=new Person();
				p.firstName=firstNameArr[Math.floor(Math.random()*firstNameArr.length)];
				p.lastName=lastNameArr[Math.floor(Math.random()*lastNameArr.length)];
				p.age=Math.floor(Math.random()*ageMax);
				personArr[i]=p;
			}
			
			trace(personArr);
			
			personArr.sort(comparePerson);
			
			trace(personArr);
		}
		
		private function comparePersonAge(a:Person,b:Person):int
		{
			if(a.age>b.age)return 1;
			else if(a.age<b.age)return -1;
			return 0;
		}
		
		private function comparePersonFirstName(a:Person,b:Person):int
		{
			if(a.firstName>b.firstName)return 1;
			else if(a.firstName<b.firstName)return -1;
			return 0;
		}
		
		private function comparePersonLastName(a:Person,b:Person):int
		{
			if(a.lastName>b.lastName)return 1;
			else if(a.lastName<b.lastName)return -1;
			return 0;
		}
		
		private function comparePerson(a:Person,b:Person):int
		{
			var result:int=0;
			
			// : : , :FirstName 
			// , 。
			result=comparePersonFirstName(a,b);
			if(result!=0)return result;
			
			result=comparePersonLastName(a,b);
			if(result!=0)return result;
			
			result=comparePersonAge(a,b);
			if(result!=0)return result;
			
			return 0;
		}
	}
}

class Person
{
	public var lastName:String;
	
	public var firstName:String;
	
	public var age:uint;
	
	public function toString():String
	{
		return firstName+"."+lastName+" age:"+age;
	}
}

出力:
Harry.D age:43,Waston.FF age:35,Waston.EE age:136,Jave.FF age:94,John.BB age:135,Waston.CCC age:41,Bill.GG age:139,John.BB age:93,Waston.FF age:44,Jave.HH age:65
Bill.GG age:139,Harry.D age:43,Jave.FF age:94,Jave.HH age:65,John.BB age:93,John.BB age:135,Waston.CCC age:41,Waston.EE age:136,Waston.FF age:35,Waston.FF age:44