What is the most efficient way to group elements in an Array by their shared property value and push them into a new Array as a single element?

Is there a way to group elements in an Array by their property value and put them into a new element, then push that new element into a new Array?

data = [
    {status: 0,name:'a'},
    {status: 0,name:'b'},
    {status: 1,name:'b'},
];

var newData = [
           {
               id: 0,
                name: 'a',
                    services: [
                        {id: 'a', name: 'a',status: 0}
                    ]
                },
                {
                    id: 1,
                    name: 'b',
                    services: [
                        {id: 'b', name: 'b',status: 0},
                        {id: 'b', name: 'b',status: 1},
                    ]
                }
            ]

Answer №1

To organize the items into groups with the same name, you can utilize a hash table as a reference and then add the actual item to the 'services' array.

var data = [{ status: 0, name: 'a' }, { status: 0, name: 'b' }, { status: 1, name: 'b' }],
    grouped = data.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.name]) {
                hash[a.name] = { id: a.name, name: a.name, services: [] };
                r.push(hash[a.name]);
            }
            a.id = a.name;
            hash[a.name].services.push(a);
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

The id property starts counting from zero in this scenario.

var data = [{ status: 0, name: 'a' }, { status: 0, name: 'b' }, { status: 1, name: 'b' }],
    grouped = data.reduce(function (hash, id) {
        return function (r, a) {
            if (!hash[a.name]) {
                hash[a.name] = { id: id++, name: a.name, services: [] };
                r.push(hash[a.name]);
            }
            a.id = a.name;
            hash[a.name].services.push(a);
            return r;
        };
    }(Object.create(null), 0), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

var inputData = [
             {status: 0,name:'apple'},
             {status: 0,name:'banana'},
             {status: 1,name:'banana'}
         ];
var outputData = [];
var index=0;
inputData.forEach(function(data){
                           var matchingElem = outputData.find(function(element){
                           return element.name === data.name;
             });

if(matchingElem) 
  {
    matchingElem.services.push({
                        "id":data.name,
                        "name": data.name,
                        "status": data.status
                      });
  }
  else{
           outputData.push({
                      "id":index++,
                      "name":data.name,
                      "services": [{
                                 "id":data.name,
                                 "name": data.name,
                                 "status": data.status
                               }]
                    });
     }

});
console.log(JSON.stringify( outputData ));

Answer №3

data = [
{status: 0,name:'a'},
{status: 0,name:'b'},
{status: 1,name:'b'}, 
];

NewData=data.reduce((newobj,obj)=>((newobj[obj.name]=newobj[obj.name]||[]).push(obj),newobj),{});

The newly transformed data structure, NewData, will now look like this:

{
    "a":[
      {status: 0,name:'a'},
    ],
    "b":[
      {status: 0,name:'b'},
      {status: 1,name:'b'}, 
    ]
}

If you want to see the code in action, check out this link.

To achieve the desired result, you need to place each object from the old array into the corresponding obj.name array of the new object. If the array does not exist yet, create a new one with ' ||[] ' method. Some formatting may still be required to tailor the output further to your needs.

Answer №4

Try out this method

  • Start by creating a mapping of name with an array of corresponding statuses.
  • Go through the map and build the array accordingly.

EXAMPLE

var data = [
    {status: 1, name:'x'},
    {status: 0, name:'y'},
    {status: 1, name:'z'},
];

var map = {};
data.forEach( function(item){
 map[ item.name ] = map[ item.name ] || [];
 map[ item.name ].push( item );
});

var newData = Object.keys( map ).map(function(name, index){
  var arr = map[ name ];
  arr = arr.map( function(arrItem){ arrItem.refId = arrItem.status; return arrItem });
  return { refId : index, title : name, entries : arr };
});

console.log(newData);

Answer №5

    var elements = [
        {status: 0, name:'a'},
        {status: 0, name:'b'},
        {status: 1, name:'b'}
    ];

    var idNumber = 0;
    var newData = elements.reduce(function(accumulator, current) {
      var item = accumulator.find(element => {
        return element.name === current.name
      });
      if (item) {
        item.services.push({
          id: current.name,
          name: current.name,
          status: current.status
        })
      } else {
        accumulator.push({
          id: idNumber++,
          name: current.name,
          services: [{
            id: current.name,
            name: current.name,
            status: current.status
          }]
        })
      }
      return accumulator;
    }, []);
    
    console.log(newData)

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

Is it possible for JavaScript to be cached when it is located within the body tag of an HTML document?

Currently, I am exploring the topic of How to optimize HTML rendering speed, and came across the idea that scripts in the HEAD tag can be cached. I'm curious, is it possible to cache JavaScript in the BODY tag? If not, I wonder why YUI suggests placi ...

Utilizing JSON data from Jade in local JavaScript: A comprehensive guide

Attempting to utilize a JSON object (the entire object, not just a portion) from Node via Jade in my local myScript.js. Here is what my Jade file looks like: span(class="glyphicon glyphicon-pencil" onclick="confirm(\"#{myJSON.taskid}\", \" ...

Tips on sending form data, including a file, to Ajax using the onclick() method

My Modal Includes a Form: <div class="modal fade bs-example-modal-lg" id="myMODALTWO" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="form-content"> <div class="modal-dialog modal-lg" role="document"> ...

Exploring Json parsing in Python with Django

I am currently using Django for my web application. I am facing an issue where I cannot access Nodes and edges by calling decoded_data['nodes']. Instead, I am encountering the error message: 'NoneType' object is not subscriptable Thi ...

Tracking mouse movement: calculating mouse coordinates in relation to parent element

I am facing an issue with a mousemove event listener that I have set up for a div. The purpose of this listener is to track the offset between the mouse and the top of the div using event.layerY. Within this main div, there is another nested div. The prob ...

Having trouble getting the JavaScript slider to animate

My code works perfectly in Codepen but when I try to implement it on my website, it shows as a static image. You can view the code here: https://codepen.io/anon/pen/zPMKpv I'm using the exact same code on my website located at: Does anyone have any ...

Is it possible to verify if a web application is currently active on a different browser tab?

My web application is built using ASP.Net/C# and Javascript and relies on session variables. I am wondering if there is a way to detect if the application is already open in another tab when I launch it? Alternatively, do you have any suggestions for ens ...

Triggering form submission through JavaScript by simulating keypress Enter does not work

Looking to incorporate some jQuery script into a website featuring keyword searching. I've encountered an issue where, upon inserting the code below into amazon.com to designate a keyword and simulate pressing the enter key using jQuery, the form fail ...

What is the best way to adjust the camera position in three.js while keeping it from rotating?

I've been working on an interface using three.js and the CSS3DObject rendering tool. To control movement, I've disabled rotation by setting the orbit to 0, allowing only panning and zooming. Just a heads up - I'm also utilizing Orbit Contro ...

Enhance your Rails application by dynamically updating table cells with Ajax, eliminating the need for

In my index.html.erb file, I have set up one form and one table. Using Ajax allows me to submit the form without any redirects. <%= form_for approval, remote: true do |f| %> <%= f.check_box :pass %> <%= f.submit%> <% end %> My ...

Unable to use .ajax within autocomplete function

I've been struggling for days to make the jQuery autocomplete feature work. Currently, I am able to type in the textbox and see exactly what I want, but the issue arises when I click on the desired option - it does not show up in the textbox. I suspec ...

Can you explain the distinction between using <router-view/> and <router-view></router-view>?

In various projects, I have encountered both of these. Are they just "syntactic sugar" or do they hold unique distinctions? ...

What is the best way to automatically adjust a panel's width and height based on the user's screen resolution?

My page is connected to a masterpage. Within this page, I have an update panel that contains an ASP.NET panel. The panel includes a gridview displaying data from the database. Currently, I have set a fixed width and height for the panel. However, if the u ...

Using jQuery to create sliding animations with left and right transitions

I recently learned about the slideUp and slideDown functions in jQuery. Are there any similar functions or methods for sliding elements to the left or right? ...

Doing an asynchronous function in the route.js file in Node.js

I'm facing an issue with my application that uses nodejs as the backend and has some Python scripts integrated. The problem lies in making the 'PythonShell' function asynchronous, but for some reason, it's not working as expected. In o ...

Error with ThreeJs OrbitControls.js functionality not operating as expected

Despite my efforts to utilize OrbitControls.js from ThreeJs by creating a folder and saving necessary files (such as GLTFLoader.js, OrbitControls.js), I encountered errors when trying to use functions within them. This led to frustrations like the one show ...

Why does this image slider begin with blankness?

For my recent school project, I created an image slider. However, upon starting the page or reloading it, only the arrows and dots are displayed. View screenshot of the issue Below is the code snippet: // JavaScript function to control the slideshow sho ...

Angular directive for resizing C3 charts

I've recently implemented a basic donut chart using C3, which I've enclosed in a directive and everything is functioning smoothly. Below is the code for my directive: angular.module('dashboardApp').directive('donutChart', fu ...

I am looking for a way to locate all meta tags that begin with either "ABC_" or "XYZ_" by using jQuery

I am facing a challenge with multiple <meta> html tags. My task is to utilize jQuery to retrieve all the meta tags where the name begins with "ABC_" or "XYZ_", and then iterate through them. This is what I have accomplished so far: var tags = $( "m ...

When dealing with arrays, the parentElement.remove() function may not be defined

Query: e1.parentElement.remove(); is not defined debug: e1 contains a value. e1.remove() removes a button, however, I need to remove a group of buttons. global variable and function execution var x = 0; AllResponses(null, null); primary function featuri ...