Skip to content Skip to sidebar Skip to footer

Group Javascript Items By One Property

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 javas

Solution 1:

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 objectvarlength= Code.length;
varresult= {};

       // Iterate over each array item// If we come across a new code, //    add it to result with an empty arrayfor(vari=0; i < length; i++) {
    if(Code[i] inresult== 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"}
         ]
}

Solution 2:

  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:

functiontoGroups(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.

Post a Comment for "Group Javascript Items By One Property"