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

Creating dynamic variable names in JavaScript can be a powerful tool to enhance

I am currently facing a challenge where I need to generate variables dynamically within a loop. I have been researching different methods, including using the eval(); function, but most of what I found only focuses on changing the value inside an existing ...

Retrieving the checkbox's status from the database

I have implemented a basic checkbox that updates its state in the database when clicked or unclicked. Is there a way to retain this state and have it displayed as checked if the page is refreshed? Essentially, I want the checkbox to remember its last state ...

Best practices for using parent and child methods in Vue applications

I'm exploring the most effective approach to creating a modal component that incorporates hide and show methods accessible from both the parent and the component itself. One option is to store the status on the child. Utilize ref on the child compo ...

Exploring AngularJS: A Guide to Accessing Millisecond Time

Is there a way to add milliseconds in Time using AngularJS and its "Interval" option with 2 digits? Below is the code snippet, can someone guide me on how to achieve this? AngularJs Code var app = angular.module('myApp', []); app.controller(&ap ...

Tips for creating a universal function for two interlinked types

My goal is to establish an abstract relationship between different sub-types of Message and Response, allowing for a generic function that takes a Message as input and returns a corresponding Response. Specifically, when the function is called with type Me ...

I am experiencing an issue in my React application where the component is not being rendered when using a nested route with React Router Dom v6. Despite the

On my main page, I have a sidebar and a content display area that shows the selected option. The issue arises when I click on a link in the sidebar - it doesn't change anything in the content display section, only the URL changes. If I define the rout ...

Construct object in JavaScript recursively

My current project involves creating a file structure index using nodeJS. I am utilizing the fs.readir function to iterate through files and it is working smoothly. However, I am facing an issue when it comes to descending into the directory structure and ...

"Is there a way to retrieve the CSS of all elements on a webpage by providing a URL using

Currently, I am in the process of creating a script that can crawl through all links provided with a site's URL and verify if the font used on each page is helvetica. Below is the code snippet I have put together (partially obtained online). var requ ...

Laravel integration with JsGrid

I'm relatively new to JsGrid and I'm attempting to implement certain functionalities similar to the one demonstrated at this link in a Laravel project. However, I encountered an error stating "Undefined index: id". I'm trying to retrieve dat ...

Trigger a page refresh when you revisit it

Currently, I am utilizing Nuxt in SPA mode and my page structure is set up like this: pages ... - users/ - - index - - new - - update/ - - - _id ... I have a page dedicated to displaying a list of users along with a 'subpage' for adding new u ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...

Obtaining documents through Mojolicious

Just a quick inquiry - I have successfully generated a .doc file using my mojolicious app with the help of the CPAN module MsOffice::Word::HTML::Writer. Now, the challenge I'm facing is figuring out how to make the browser initiate the download proces ...

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

Performing a search within a JSON data column in MySQL

I'm currently facing a challenge with my MySQL database column that stores JSON array encoded strings. My goal is to search within the JSON array for values where the "Elapsed" is greater than a specific number and then retrieve the corresponding Task ...

Javascript error: The variable calculator_test has not been defined

Why am I receiving an error message: Uncaught ReferenceError: calculator_test is not defined index.html: <!DOCTYPE html> <html> <body> <p>Click the button</p> <button onclick="calculator_test()">test</button> &l ...

Locate the nearest neighbor for each given point to find the closest point

We have a method that takes an array of points as input and aims to find, for each point in the array, the closest point to it (excluding itself). Currently, this process involves a brute force approach of comparing every point with every other point. The ...

Creating eye-catching designs for Material grid-list items

Here is the code snippet for generating a list: <md-grid-list cols="5" rowHeight="20px"> <md-grid-tile *ngFor="let carBrand of carBrands" colspan= 1 rowspan= 1> <md-checkbox>{{ carBrand}}< ...

Tips for accessing data directly from a database rather than relying on JSON for every request

After watching a tutorial on YouTube, I was inspired to create a way to deliver articles from a WordPress blog using the JSON API. You can check out the GITHUB link for more details. The tutorial provided a good example, but it only showed data from the d ...

What is the reason behind my button appearing beneath my links in React?

Here is an image showcasing the current header render. The header consists of a HeaderMenu and 3 Links. While the links are functioning properly, the HeaderMenu is causing the links to be positioned below it. The HeaderMenu includes a div that wraps a Butt ...

The error "req.user is not defined" occurs when accessing it from an Android

I am currently collaborating with an Android developer to create an android app. While my colleague handles the front-end development, I focus on the backend work. Specifically, I have implemented the login and authentication features using node.js, expres ...