Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format:

[
  {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"},
  {grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1"},
  {grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1,  type: "Type_1"},
  {grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2"},
  {grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2"}
]

Thanks to a helpful article on a programming forum, I've managed to reorganize my data to group each item by its type like this:

var DATA_API = [
  {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"},
  {grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1"},
  {grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1,  type: "Type_1"},
  {grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2"},
  {grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2"}
];

Array.prototype.groupBy = function(key) {
      return this.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc),{});
};

FORMATTED_DATA = DATA_API.groupBy("type")
console.log(FORMATTED_DATA)

However, I'm facing an issue using this formatted result in an angular material mat-table as it requires an array and not an object.

Error: Provided data source did not match an array, Observable, or DataSource

How can I retrieve a list that consists of multiple nested lists instead?

[
  [
    {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"},
    {grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1"},
    {grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1,  type: "Type_1"}
  ],
  [
    {grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2"},
    {grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2"}
  ]
]

Thank you for your assistance.

Answer №1

You can extract the values from the object.

Array.prototype.groupBy = function(key) {
    return this.reduce((acc, item) => (acc[item[key]] = [...(acc[item[key]] || []), item], acc), {});
};

var API_DATA = [{ grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1" }, { grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1" }, { grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1,  type: "Type_1" }, { grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2" }, { grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2" }],
    TABLE_DATA = Object.values(API_DATA.groupBy("type"));

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

UPDATE 2023

Using the new standard Object.groupBy:

const
    API_DATA = [{ grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1" }, { grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1" }, { grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1,  type: "Type_1" }, { grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2" }, { grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2" }],
    TABLE_DATA = Object.values(Object.groupBy(API_DATA, ({ type }) => type));

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

Answer №2

You have the option to group this information in two different ways.

  • The first method involves grouping it as an object
  • The second approach is to group it as an array

Example

NOTE: The output is formatted using JSON.stringify(group, null, 2).

const API_DATA = [
    { grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1" },
    { grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1" },
    { grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1, type: "Type_1" },
    { grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2" },
    { grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2" }
];

const groupBy = 'type';

console.log('------------------');
console.log('------Object------');
console.log('------------------');

const group1 = {};
for (let i = 0; i < API_DATA.length; i++) {
    const element = API_DATA[i];
    const groupByValue = element[groupBy];

    if (typeof group1[groupByValue] === 'undefined') {
        group1[groupByValue] = [element];
    } else {
        group1[groupByValue].push(element);
    }
}
console.log(JSON.stringify(group1, null, 2))



console.log('-------------------');
console.log('-------Array-------');
console.log('-------------------');

const group2 = [];
const tmp = {};
for (let i = 0; i < API_DATA.length; i++) {
    const element = API_DATA[i];
    const groupByValue = element[groupBy];

    if (typeof tmp[groupByValue] === 'undefined') {
        const position = group2.length; // get new position
        tmp[groupByValue] = position; // save it
        group2[position] = [element];
    } else {
        const position = tmp[groupByValue];
        group2[position].push(element);
    }
}
console.log(JSON.stringify(group2, null, 2))

Answer №3


    Extending Array.prototype with a groupBy method to organize data by a specified key:

    Array.prototype.groupBy = function (key) {
      return this.reduce(
        (acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc),
        []
      );
    };

Answer №4

Utilize the _.groupBy() function provided by lodash

var jsonArray = [
  {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"},
  {grade: "Grade B", id: 2, ifsGrade: "B1XX", ifsType: "02XX", points: 15, type: "Type_1"},
  {grade: "Grade C", id: 3, ifsGrade: "C1XX", ifsType: "03XX", points: 1,  type: "Type_1"},
  {grade: "Grade A", id: 4, ifsGrade: "A2XX", ifsType: "04XX", points: 23, type: "Type_2"},
  {grade: "Grade B", id: 5, ifsGrade: "B2XX", ifsType: "05XX", points: 26, type: "Type_2"}
]


var groupJson= _.groupBy(jsonArray, function(jsonArray) {
  return jsonArray.type;
});

console.log(groupJson);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

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

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

data being returned twice onpopstate

After experimenting with onpopstate, I encountered an issue. When I click the back button in my browser, the URL changes as expected, but the page code loads twice, resulting in duplicate lists and div elements. Why is this happening and how can it be reso ...

The architecture of Angular controllers

Being a novice in AngularJs, I have a query regarding the controller structure. This particular file is my employeeController.js (function() { angular.module('employeeApp').controller('employeeController', employeeCont ...

What is causing the extra space on the right side of the box?

I've been struggling to align text next to an image inside a box. Desired outcome CSS: #roundedBox { border-radius: 25px; background: #363636; width: auto; height: auto; margin: 10%; display: flex; position: relative; ...

React JS progress circle bar is a simple and effective way to visualize

Currently, I am in the process of developing a progress circle bar that will function as a timer alongside sliders. Each slide is intended to have its own corresponding progress bar. While I have managed to create the bars individually, I am facing challe ...

Change mailchimp3 client.lists.members.all into a dataframe or csv using Python

Looking for help with the mailchimp3 library and connecting to Mailchimp via API. I'm able to retrieve data with the request below, but I'm having trouble manipulating the data once it's stored in a variable. from mailchimp3 import MailChimp ...

Creating dynamic charts in Javascript using Firebase

My dad recently asked me to enhance our motor home by integrating an Arduino with Firebase to monitor the water and propane tanks. He's hoping to be able to check tank levels from his phone so he can see when they need refilling. I've successful ...

Angular: The unexpected emergence of certificate issues and the ensuing challenges in resolving them

After completing the first two chapters of Google's Tour of Heroes, I repeated the process 21 times without any major issues. However, when attempting to run it for the 22nd time on the same machine and with the same Visual Studio setup, I encountered ...

Using Jquery's $.each() method within an ajax call can be a powerful

Is it possible for a jQuery each loop to wait for Ajax success before continuing when sending SMS to recipients from an object? I want my script to effectively send one SMS, display a success message on the DOM, and then proceed with the next recipient. O ...

What is the process for creating a selector that links to an element that has been dynamically generated?

Can anyone help me figure out how to create a selector that links to a dynamically created element without using an event on the dynamic element? By dynamically created element, I mean an element that is not present in the HTML at the beginning. I know t ...

The issue encountered is when the Ruby posting field appears as an empty JSON object during the

Update: Below are the details of the POST data and ruby log that I have been examining: Ruby log: Started PUT "/things/1" for 127.0.0.1 at 2014-10-28 10:54:32 -0700 Processing by ThingController#update as JSON Parameters: { "name"=>"Name", "im ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

What steps should I take to set up search paths for node modules in Code Runner within Visual Studio Code?

Just recently, I embarked on a Javascript course and successfully configured my Visual Studio Code to run JavaScript. Check out the code snippet that I came up with: const prompt = require('prompt-sync')(); var fname = prompt("First name please : ...

Tips on showcasing Javascript filter outcomes after at least 2 characters have been entered

Currently, I have implemented a filter search box that displays results as soon as a single letter is inputted. However, due to the large amount of data that needs to be filtered through, I would like the search to only show results when a minimum of two l ...

Preventing blank text entries in a task management application

Is there a way to determine if the text input provided by the user is empty or contains some text? I'm in the process of developing a TO-DO app and I'd like it so that if a user fails to enter anything into the text area and clicks on "add", the ...

Webpack focuses solely on serving HTML files, neglecting to deliver the underlying code

Hey there! I'm currently working on a project that involves using React, TypeScript, and Webpack. I ran into some errors previously that prevented the code from compiling, but now that's fixed. However, when I run webpack, it only serves the HTML ...

Utilizing jQuery UI for Autocomplete Functionality with Objects

Currently, I am utilizing jQuery version 1.11.2 and attempting to implement the autocomplete widget to interpret a data array. The array consists of two individuals - Will Smith and Willem Dafoe. I anticipated that upon typing 'Wi' in the text fi ...

powershellUsing the cURL command with a PHP script

I am having trouble sending JSON data from the command line with curl to a php script and properly receiving it on the server-side. Here is what I have attempted so far: Running the following command in the command line: curl -H "Content-Type: applicati ...

Conceal a column within a nested HTML table

I am facing a challenge with a nested table column structure: My goal is to hide specific columns based on their index within the table. Can someone explain the concept behind achieving this? I am unsure of how to get started on this task. <table clas ...

What is the best way to prevent event propagation in d3 with TypeScript?

When working with JavaScript, I often use the following code to prevent event propagation when dragging something. var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on('dragstart', function(e) { d3.event.sourceEvent ...