彩音 - Adobe AIR - 研究室:XION -Adobe AIR-laboratory
配列の要素がオブジェクトのとき、オブジェクトの値でソートする sortOn()

配列に入っている値がオブジェクトの場合、sortOn() を使用すればオブジェクトのプロパティ値でオブジェクトを並び替えることができる。並び替えるキーになるプロパティは全てのオブジェクトで共通のプロパティである必要がある。この共通プロパティのことをフィールドと呼ぶ。


var goods:Array = new Array();
goods.push({id:"bee", price:210});
goods.push({id:"xox", price:100});
goods.push({id:"zizi", price:280});
goods.push({id:"abic", price:180});
goods.sortOn("price", Array.NUMERIC);

for (var i:uint = 0; i < goods.length; i++) {
trace (goods[i].id, goods[i].price);
}

出力結果


xox 100
abic 180
bee 210
zizi 280

複数のソートキーを指定したい場合、キーを["color", "price"]のように配列で指定する。降順といったオプションを指定したい場合、オプションを配列にして第二引数で指定する。このとき、ソートキーの個数とオプションの個数が同じでなくてはならない。文字順を指定したい場合のオプションは0である。


var goods:Array = new Array();
goods.push({id:"be10", price:210, color:"red"});
goods.push({id:"xo02", price:100, color:"blue"});
goods.push({id:"zic9", price:290, color:"red"});
goods.push({id:"abi50", price:180, color:"blue"});
goods.push({id:"abi49", price:280, color:"red"});
goods.push({id:"abi51", price:150, color:"blue"});
goods.sortOn(["color", "price"], [0, Array.NUMERIC]);

for (var i:uint = 0; i < goods.length; i++) {
trace(goods[i].id, goods[i].price, goods[i].color);
}

出力結果


xo02 100 blue
abi51 150 blue
abi50 180 blue
be10 210 red
abi49 280 red
zic 290 red

以下の例は並び替えオプションのArray.RETURNINDEXEDARRAY (8) を使った例である。並び替えた場合の結果のインデックス番号に基づいて値を取り出している。元の配列を並び替えたくない場合にこのオプションを利用する。Array.RETURNINDEXEDARRAY は1番目のキーにのみ利用出来るオプションである。価格は数値で降順になるように Array.DESCENDING (2) のオプションを追加している。


var goods:Array = new Array();
goods.push({id:"be10", price:210, color:"red"});
goods.push({id:"xo02", price:100, color:"blue"});
goods.push({id:"zic9", price:290, color:"red"});
goods.push({id:"abi50", price:180, color:"blue"});
goods.push({id:"abi49", price:280, color:"red"});
goods.push({id:"abi51", price:150, color:"blue"});

var indexlist:Array = goods.sortOn(["color", "price"], [0|8, 16|2]);
var index:uint;

for (var i:uint = 0; i < goods.length; i++) {
index = indexlist[i];
trace (goods[index].id, goods[index].price, goods[index].color;
}

出力結果


abi50 180 blue
abi51 150 blue
xo02 100 blue
zic9 290 red
abi49 280 red
be10 210 red

索引