按特定值对多维数组进行分组

时间:2014-04-22 04:31:45

标签: arrays actionscript-3

我有一个多维数组,我正在尝试根据数组属性的值对它们进行分组。

我正在尝试按ID分组,但我事先并不会真正知道id。所以,这并不是说我可以把它放在for循环中然后说我同时7,因为我不知道7是id值的最大值,

Array (
 [0] => Array (
      [name] => R8900
      [type] => public
      [id] => 1
      )
[1] => Array (
      [name] => R8944
      [type] => public
      [id] => 1
      )
[2] => Array (
      [name] => R8922
      [type] => private
      [id] => 3
      )
[3] => Array (
      [name] => R8816
      [type] => private
      [id] => 3
      )
 [4] => Array (
      [name] => R7434
      [type] => VIP
      [id] => 7
      )
)

我希望制作的内容:

Array (

[1] => Array (
      [0] => Array (
                [name] => R8900
                [type] => public
                )
      [1] => Array (
                [name] => R8944
                [type] => public
                )
      )

 [3] => Array (
      [2] => Array (
             [name] => R8922
             [type] => private
             )

      [3] => Array (
             [name] => R8816
             [type] => private
             )
      )

 [7] => Array (
      [4] => Array (
             [name] => R7434
             [type] => VIP
             )
      )
)

1 个答案:

答案 0 :(得分:1)

简单的事情:

var result:Object = {};

for each(var i:Object in input)
{
    if(!result.hasOwnProperty(i.id))
    {
        result[i.id] = [];
    }

    result[i.id].push(i);
    delete i.id;
}