0

I have a multidimensional array and am trying to group them according to the value of array properties.

I'm trying to group them by id, but I won't actually know the id beforehand. So, it's not like I can put it in a for loop and say while i < 7, because I won't know that 7 is the maximum value for the id value,

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
      )
)

What I'm hoping to produce:

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 Answer 1

1

Something as simple as:

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;
}
Sign up to request clarification or add additional context in comments.

9 Comments

How can I trace the "result" property?
@xyonme Because result and its contents are Objects, you need to iterate over the contents to debug it. Alternatively, you could create a custom data type for result and the inner objects with your own toString() definitions.
the delete statement : is it deleting the whole object? why do we delete the object. The result in Array would be best?
@xyonme I don't delete the whole object... It only deletes the id property because in your question your desired output did not contain it.
Ah yes yes. what about the array result? would u show me how to do the result as an Array , not as an Object?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.