Organize arrays within arrays in Javascript

My array of data is structured for visualization as shown below:


var Dataset1 = [
  {
    "commentBy": "saurabh",
    "comment": "Testing",
    "datestamp": "07/07/2017",
    "weekcount": 1
  },
  {
    "commentBy": "raman",
    "comment": "Planning",
    "datestamp": "07/07/2017",
    "weekcount": 1
  },
  {
    "commentBy": "Execution",
    "comment": "Alfa Beta",
    "datestamp": "07/07/2017",
    "weekcount": 2
  },
  {
    "commentBy": "Execution",
    "comment": "Zseta Gama",
    "datestamp": "07/07/2017",
    "weekcount": 2
  }
]

// Despite attempting to create a function, the desired result has not been achieved.

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
var groubedByTeam = groupBy(Dataset1, 'weekcount')
console.log(groubedByTeam);

In order to group the dataset by weekcount, I wish to see the following result:

[
  {
    "weekcount": 1,
    "grouped": [
      {
        "commentBy": "saurabh",
        "comment": "Testing",
        "datestamp": "07/07/2017"
      },
      {
        "commentBy": "raman",
        "comment": "Planning",
        "datestamp": "07/07/2017"
      }
    ]
  },
  {
    "weekcount": 2,
    "grouped": [
      {
        "commentBy": "Execution",
        "comment": "Alfa Beta",
        "datestamp": "07/07/2017"
      },
      {
        "commentBy": "Execution",
        "comment": "Zseta Gama",
        "datestamp": "07/07/2017"
      }
    ]
  }
]

Answer №1

const formattedData = [];

Dataset1.forEach((data) => {
  const { weekCount, commentText, commenterName, timeStamp } = data;
  let obj = formattedData.find((item) => item.weekCount === weekCount);

  if (!obj) {
    formattedData.push({
      weekCount,
      groupedData: [{
        commentText,
        commenterName,
        timeStamp
      }]
    })
  } else {
    obj.groupedData.push({
      commentText,
      commenterName,
      timeStamp
    });
  }
});

const Dataset1 = [{
  "commenterName": "saurabh",
  "commentText": "Testing",
  "timeStamp": "07/07/2017",
  "weekCount": 1
}, {
  "commenterName": "raman",
  "commentText": "Planning",
  "timeStamp": "07/07/2017",
  "weekCount": 1
}, {
  "commenterName": "Execution",
  "commentText": "Alfa Beta",
  "timeStamp": "07/07/2017",
  "weekCount": 2
}, {
  "commenterName": "Execution",
  "commentText": "Zseta Gama",
  "timeStamp": "07/07/2017",
  "weekCount": 2
}];

const formattedData = [];

Dataset1.forEach((data) => {
  const { weekCount, commentText, commenterName, timeStamp } = data;
  let obj = formattedData.find((item) => item.weekCount === weekCount);

  if (!obj) {
    formattedData.push({
      weekCount,
      groupedData: [{
        commentText,
        commenterName,
        timeStamp
      }]
    })
  } else {
    obj.groupedData.push({
      commentText,
      commenterName,
      timeStamp
    });
  }
});

console.log(formattedData);

Answer №2

Here's a great method to group your data efficiently, allowing you to easily customize the formatting according to your preferences using this initial structure.

groupedData = {}

Dataset1.forEach(function(entry, position){

    if (!groupedData[entry.weeknumber]) groupedData[entry.weeknumber] = [];
    groupedData[entry.weeknumber].push(entry);

});

The groupedData object is organized based on week numbers. If a particular week number isn't present as a key in the object, an empty array is generated and the relevant data is subsequently added. Subsequent data with the same week number is appended to the existing array during subsequent iterations.

Answer №3

To iterate through each week count from 0 to the maximum value and filter the array accordingly, you can use the following approach:

var Data =  [
      {
        "commentBy" : "Alice",
        "comment" : "Reviewing",
        "datestamp" : "07/08/2017",
        "weekcount" : 1
      },

       {
        "commentBy" : "Bob",
        "comment" : "Implementing",
        "datestamp" : "07/08/2017",
        "weekcount" : 1
      },
       {
        "commentBy" : "Charlie",
        "comment" : "Testing",
        "datestamp" : "07/08/2017",
        "weekcount" : 2
      },
        {
        "commentBy" : "Dave",
        "comment" : "Debugging",
        "datestamp" : "07/08/2017",
        "weekcount" : 2
      } 
        ]

var maxWeekCount = 4;
var output = []
for(var j=0; j<maxWeekCount; j++){
  var groupedData = Data.filter(object => object.weekcount === j)
  if(groupedData.length) {
    output.push({
      weekNumber: j,
      dataGroup: groupedData
    })
  }
}

console.log(output)

Answer №4

Utilize a helper entity that maintains a connection to the weekcount objects in order to condense the array into a grouped structure.

var Dataset1 = [{"commentBy":"saurabh","comment":"Testing","datestamp":"07/07/2017","weekcount":1},{"commentBy":"raman","comment":"Planning","datestamp":"07/07/2017","weekcount":1},{"commentBy":"Execution","comment":"Alfa Beta","datestamp":"07/07/2017","weekcount":2},{"commentBy":"Execution","comment":"Zseta Gama","datestamp":"07/07/2017","weekcount":2}];

var helperMap = {};

var result = Dataset1.reduce(function(arr, obj) {
  var current = helperMap[obj.weekcount];
  
  if(!current) {
    current = { 
      weekcount: obj.weekcount,
      grouped: [] 
    };
    
   helperMap[obj.weekcount] = current;
    
    arr.push(current);
  }

  current.grouped.push({
    commentBy: obj.commentBy,
    comment: obj.comment,
    datestamp: obj.datestamp
  });
  
  return arr;
}, []);

console.log(result);

Answer №5

const customGroupBy = (arr, prop) => {
  return arr.reduce((result, item) => {
    if (result[item[prop]] === undefined){
      result[item[prop]] = {"weekcount": item[prop], "grouped": []}
    }
    const stripped = {}
    for(const key in item) if(key !== prop) stripped[key] = item[key]; //strip "prop" property
    result[item[prop]]["grouped"].push(stripped);
    return result;
  }, []);
};

This innovative solution adapts to any input effortlessly by removing the specified property, ensuring it remains effective even when properties are added or removed from the input data.

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

What is the best method for directing a search URL with an embedded query string?

Currently, I am developing an express application that has two different GET URLs. The first URL retrieves all resources from the database but is protected by authentication and requires admin access. The second URL fetches resources based on a search para ...

Is there a way to transform a .pcm file to a wav file using node.js?

I'm working on a project that generates a pcm file from a stream and saves it after the stream finishes. Now, I am looking for a way to convert this .pcm file to a .wav or another audio format using an npm package. Can anyone suggest a solution or poi ...

Generating aggregated statistics from JSON logs using Apache Spark

Recently delving into the world of Apache Spark, I've encountered a task involving the conversion of a JSON log into a flattened set of metrics. Essentially, transforming it into a simple CSV format. For instance: "orderId":1, "orderData": { ...

Tips for displaying the message "{"POWER":"ON"}" within the else if statement (this.responseText == ({"POWER":"ON"})) {

Hey everyone, I'm trying to adjust the color of a button on my webpage based on the response I receive from this.responseText. I understand the JSON response, but for some reason, I can't seem to incorporate it into my code. If anyone could lend ...

Obtaining the distinct identifier of a MongoDB document during insertion

I am currently developing a NodeJS express application with MongoDB (using Mongojs) and I am facing some challenges in achieving a specific task. My issue is related to inserting an object into a collection and then obtaining the unique identifier of this ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

The newly added radio button does not function as a separate group as expected

I currently have a set of radio buttons: <input type="radio" class='form-control' name="progress_type[]" value="Journal Papers"><span class='radio-label'>Journal Paper</span> <input type="radio" class='form-co ...

Tips for optimizing the creation and compilation of expansive maps using c++

At the moment, I am dealing with multiple json files and a python script that processes one of the json files, main.json, to generate a complete c++ code based on its content. In the main() function of this c++, I have the requirement to convert a numerica ...

Exploring the capabilities of HTML5's file API along with Octokit.js to work with

I have been trying to create a form that allows users to upload binary data to GitHub using octokit.js. However, every time I attempt to do so, the data ends up corrupted on the GitHub side. Here is a minimal working example: http://jsfiddle.net/keddie/7r ...

Encountering an issue with Angular routing: Cross-origin requests are restricted to specific protocol schemes, such as HTTP

I encountered an error while working on angular routing. Below is my HTML code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <script src= ...

Consistent integration into React component

I'm currently working on an application using the React library, but my current challenge lies within JavaScript ES6 itself. Within a component (page) that I've created, I have implemented a custom Floating Action Button (FAB): class Page exten ...

Combining Vue.js for handling both enter key and blur events simultaneously

I have been working on a solution where pressing the enter key or losing focus on an element will hide it and display a message. However, I am facing an issue where when I press the enter key to hide the element, it also triggers the blur event. I only wan ...

How can I effectively utilize my JSON HTTP Request header in Swift?

Looking for a way to streamline my application that frequently interacts with an API, I want to avoid repetitive code. Can anyone suggest a more efficient method for code reuse, possibly using extensions? This is the current code snippet: func apiReques ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

how can a select dropdown be dynamically displayed based on the previous selection?

If the first dropdown is set to "Professor" I want to display a second dropdown, but if it is set to "Student" then I do not want to display the second dropdown. function checkPrivilege() { var privilege = document.getElementById("permisija5").value; ...

Upon refreshing the browser, an error pops up saying "unable to set headers after they have been sent."

Error image: app.get('/home', function (req, res, next) { usersession = req.session; if (usersession.loggedin == true) res.redirect('/home'); res.sendFile(path.join(__dirname, 'index.html')); }); ...

Prevent unauthorized users from accessing the expressjs application

Imagine you have an expressjs app set up like this: var express = require('express'); var http = require('http'); var httpApp = express(); httpApp.configure(function() { httpApp.use(express.static(__dirname + '/static/&apo ...

A guide on decoding a JSON object with a JSON array in Laravel

I created an API to retrieve data in JSON format like this: { [ { "name": "John Doe", "year": "1st", "curriculum": "Arts" } ]} The issue I'm facing is that I am unable to access any field of this data. I have tried us ...

Step-by-step guide on entering text into a hidden field with Selenium WebDriver and Java

I am currently utilizing WebDriver in conjunction with Java for automated testing. I have come across a hidden input field within the following HTML code: <input type="hidden" value="" name="body" id=":6b"> My challenge lies in trying to input data ...

Exchange information between two selected items

Below is a simplified version of the current code that I am working with: https://jsfiddle.net/2zauty83/8/ Javascript function checkboxlimit(checkgroup) { var checkgroup = checkgroup for (var i = 0; i < checkgroup.length; i++) { checkgroup[i] ...