Creating subarrays with identical strings from a given array: step-by-step guide

I currently have an array structured as follows :

[
{
    "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 there a way to create subarrays containing the same title field string?

For example, in this instance, I would like to generate:

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

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

and so forth...

If there is only one element for a particular title, it should be represented as follows:

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

I am looking for a versatile solution.

While I am aware that I could use methods such as indexOf('results') with filters, I would prefer not to hardcode specific titles since they are subject to change. Any suggestions or ideas?

Fiddle

Answer №1

If you want to organize similar items, consider utilizing an object:

var categories = {};

item_list.forEach(function(item){ 
   var category_key = item.type.split('_')[0];
   if(!categories[category_key]) {
      categories[category_key] = [];
   }
   categories[category_key].push(item);
});

To see a live demonstration in action, click here: http://jsfiddle.net/t459o6v1/3/

Answer №2

Utilize the power of .reduce() to group and organize your data efficiently

var groups = data.reduce(function(result, currentValue) {
  var key = currentValue.title.split("_")[0];

  if (typeof result[key] === "undefined") {
    result[key] = [];
  }

  result[key].push(currentValue);

  return result;
}, {});

Once grouped, consider using .map() for further transformations or operations

var subArrays = Object.keys(groups).map(function(key) {
return groups[key];
});

var data = {/* Your array of objects here */};

var groups = data.reduce(function(result, currentValue) {
var key = currentValue.title.split("_")[0];
  
  if (typeof result[key] === "undefined") {
  result[key] = [];
  }
  
  result[key].push(currentValue);
  
  return result;
}, {});

var subArrays = Object.keys(groups).map(function(key) {
return groups[key];
});

console.log(JSON.stringify(subArrays));

Answer №3

My solution involves utilizing Immutable.JS, although a similar approach could be implemented using libraries like lodash or underscore. It's important to note that this is a functional implementation, rather than imperative.

To begin, create a function to extract the prefix:

function getPrefix(name) {
    var substr = name.substring(0, name.indexOf('_'))
    return substr ? substr : name;
}

Next, apply the groupBy function:

Immutable.fromJS(arr).groupBy(element => getPrefix(element['title']))
            .toJS();

This will result in an array of arrays with the title serving as the key.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

Comma styling in JavaScript

What is the reasoning behind developers choosing to format commas in code this particular way? var npm = module.exports = new EventEmitter , config = require("./lib/config") , set = require("./lib/utils/set"); As opposed to this formatting style? va ...

Find and filter the values in the range.getValues() array that correspond to the first element in apps script

In the spreadsheet provided, I have compiled a list of cities in different states of my country. This information will be utilized in a form; however, it is not feasible for users to sift through an extensive list of all cities listed. Therefore, I am look ...

Is Angular considered bad practice due to its reliance on singletons, despite its widespread use and popularity?

Angular relies on singletons for all its services, however using singletons is often frowned upon in the development community. Despite this controversy, I personally find Angular to be a valuable and effective tool. What am I overlooking? ...

Accessing the hashtag portion of the URL in Nuxt

this.$route.path retrieves the URL without the hashcode at the end. Is there a way to obtain the hash part of the URL or the entire URL so that I can properly separate the hash part? Just to clarify, for a URL like https://example.com#test, I am trying to ...

The error message "[Insecure URL]" was triggered at line 85 of angular.min.js in the AngularJS framework

Looking for some assistance with Angular as I have limited knowledge. It was working fine on localhost, but after upgrading from PHP5 to PHP7, I encountered this error: angular.min.js:85 Error: [$sce:insecurl] http://errors.angularjs.org/1.2.13/$sce/inse ...

JavaScript creating popup windowsAlternatively: JavaScript-empowered

After spending hours searching, I still haven't found the answer I'm looking for. That's why I'm reaching out here with a question. How can I incorporate pop-up windows or click functions into an existing map like this one: ? I am aimi ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

What is the best way to extract several form elements and assign a new attribute to each of them?

<form name="myform"> <fieldset> <legend>Delivery Information</legend> <p>Country: <input pattern="^[A-Za-z]" type="text" name="textInput" size=&qu ...

JavaScript image sorting function fails to sort multiple ID elements that match

Currently, I am working on a project to develop an image sorter using toggle buttons. However, I have encountered an issue where my function is only effective for the first image ID and not any others. Below is the JavaScript function in question: functi ...

The selectors in NgRx store are failing to retrieve data from the main global store

As I delve into the world of ngrx, I find myself struggling to fully understand and implement it effectively within my application. Recently, I integrated ngrx version 8.3 into my project in hopes of organizing my state management efficiently. My goal is ...

A tip for transferring the value of a binding variable to a method within the template when the button is clicked

I am currently exploring the concept of binding between parent and child components using @Input, @Output, and EventEmitter decorators. This is demonstrated in the HTML snippet below: <h1 appItemDetails [item]="currentItem">{{currentItem}}& ...

Ways to darken a theme when displaying a pop-up

I recently added a pop-up feature to my portfolio website and utilized Bootstrap classes to enhance its functionality. In order to make the pop-up object more prominent, I wanted to darken the background when opening the pop-up. However, some elements in t ...

Creating a dynamic d3 force layout with interactive features in an Angular environment

I am currently working on a website using Angular and D3, although I don't have much experience with either of them. My goal is to create a force layout that is interactive, allowing users to select nodes and display related information in a sidebar. ...

Issue with Javascript function functionality

My animated menu has a problem where it functions correctly when sliding out, but gets stuck on the way back. Specifically, the first section (#section-1) returns perfectly, but the other two sections (#section2 and #section3) do not. Can anyone offer as ...

Validation of form inputs does not occur during typing, only when the input is blurred

Currently, I have implemented a combobox with input data validation using Vuelidate: <template> <v-combobox clearable v-model="surname" :items="commonSurnames" label="Surname" ...

Attempting to modify the Nivo slider configuration has proven to be ineffective

Can someone assist me in getting the Nivo Slider to function properly? I keep receiving a "syntax error" on the last line and can't seem to figure out what's causing it. The error occurs specifically on the line that reads: " }); " which is the ...

Adjust the Bootstrap date-time-picker to accommodate various languages, while ensuring that the selected date and time are displayed in English

As I work on my app, I've implemented localization support for multiple languages. When initializing the datetimepicker in the app, I provide the current language like this: datetimepicker({ locale: languageObj.language, format: 'DD MMM ...

Converting an AngularJS Array to Firebase JSON Format

Currently, in my application, I am working on creating an array using JS. $scope.items = []; As I add items to this array, I retrieve information from a Firebase Reference and populate the items array with it. es.addItem = function(item){ var produc ...

"Encountering issues when trying to POST data from an Ember component to an

When attempting to post from a component in my Ember app to my Express API, I am encountering the following error: SyntaxError: Unexpected token V in JSON at position 0 Upon inspecting the response in the network inspector on Chrome, I found this error m ...