views:

52

answers:

2

My question is related to this question. You will have to first read it.

var ids = "1*2*3";
var Name ="John*Brain*Andy";
var Code ="A12*B22*B22";

Now that I have an array of javascript objects. I want to group my objects based on CODE. So there can be duplicate codes in that code string.

As per the above changed strings, I have same code for Brain and Andy. So, now I want two arrays. In one there will be only one object containing details of only John and in the other object there will be two objects containing details of Brain and Andy.

Just for example I've taken 3 items. In actual there can be many and also there can be many set of distinct codes.

UPDATE
I needed the structure like the one built in groupMap object by the @Pointy. But I will use @patrick's code to achieve that structure. Many thanks to both of them.

+1  A: 
  1. Split the strings on "*" so that you have 3 arrays.
  2. Build objects from like-indexed elements of each array.
  3. While building those objects, collect a second object that contains arrays for each "Code" value.

Code:

function toGroups(ids, names, codes) {
  ids = ids.split('*');
  names = names.split('*');
  codes = codes.split('*');
  if (ids.length !== names.length || ids.length !== codes.length)
    throw "Invalid strings";

  var objects = [], groupMap = {};
  for (var i = 0; i < ids.length; ++i) {
    var o = { id: ids[i], name: names[i], code: code[i] };
    objects.push(o);
    if (groupMap[o.code]) {
      groupMap[o.code].push(o);
    else
      groupMap[o.code] = [o];
  }
  return { objects: objects, groupMap: groupMap };
}

The "two arrays" you say you want will be in the "groupMap" property of the object returned by that function.

Pointy
+1  A: 

It is a little hard to tell the exact resulting structure that you want.

This code:

       // Split values into arrays
Code = Code.split('*');
Name = Name.split('*');
ids = ids.split('*');

       // cache the length of one and create the result object
var length = Code.length;
var result = {};

       // Iterate over each array item
       // If we come across a new code, 
       //    add it to result with an empty array
for(var i = 0; i < length; i++) {
    if(Code[i] in result == false) {
        result[ Code[i] ] = [];
    }
            // Push a new object into the Code at "i" with the Name and ID at "i"
    result[ Code[i] ].push({ name:Name[i], id:ids[i] });
}

Will produce this structure:

// Resulting object
{
      // A12 has array with one object
    A12: [ {id: "1", name: "John"} ],

      // B22 has array with two objects
    B22: [ {id: "2", name: "Brain"},
           {id: "3", name: "Andy"}
         ]
}
patrick dw