Search code examples
javascriptarraysgroupingsub-array

How to make subarrays containing a same string from an array?


I have an array like this :

[
{
    "title": "name",
    "value": ""
},
{
    "title": "version",
    "value": ""
},
{
    "title": "inventory_name",
    "value": ""
},
{
    "title": "inventory_version",
    "value": ""
},
{
    "title": "differed",
    "value": ""
},
{
    "title": "differed_name",
    "value": ""
},
{
    "title": "accept_error_while_reboot",
    "value": ""
},
{
    "title": "setup_check",
    "value": ""
},
{
    "title": "setup_install",
    "value": ""
},
{
    "title": "setup_install_partial",
    "value": ""
},
{
    "title": "params_install",
    "value": ""
},
{
    "title": "params_install_partial",
    "value": ""
},
{
    "title": "results_install_ok",
    "value": ""
},
{
    "title": "results_install_reboot_defered",
    "value": ""
},
{
    "title": "results_install_reboot_immediate",
    "value": ""
},
{
    "title": "results_install_partial_ok",
    "value": ""
},
{
    "title": "results_install_partial_reboot_defered",
    "value": ""
},
{
    "title": "results_install_partial_reboot_immediate",
    "value": ""
}
];

Is it possible to make subarrays that contains the same title field string ?

For example in this case , I will have :

array1 = [
 {
  "title": "differed",
  "value": ""
 },
 {
  "title": "differed_name",
  "value": ""
 }
]

array2 = [
 {
  "title": "setup_check",
  "value": ""
 },
 {
  "title": "setup_install",
  "value": ""
 },
 {
  "title": "setup_install_partial",
  "value": ""
 }
]

and so on...

In case of single elements , I should have :

[
 {
 "title": "name",
 "value": ""
 }
]

I'm searching for a generic approach.

I know I can use, for example, indexOf('results') with filter function, however I'd like if it's possible to avoid the hardcode since it's not always the same titles.

Any ideas ?

Fiddle


Solution

  • You can use an object to group similar items:

    var groups = {};
    
    parameter_list.forEach(function(p){ 
       var key = p.title.split('_')[0];
       if(!groups[key]) {
          groups[key] = [];
       }
       groups[key].push(p);
    });
    

    Working demo: http://jsfiddle.net/t459o6v1/3/