What is the best method to extract the values of objects in an array that share

 var data= [{tharea: "Rare Disease", value: 3405220},
           {tharea: "Rare Disease", value: 1108620},
           {tharea: "Rare Disease", value: 9964980},
           {tharea: "Rare Disease", value: 3881360},
           {tharea: "Rare Disease", value: 4090880},
           {tharea: "Rare Disease", value: 1657600}];

The desired output for the object would be:

data=[{tharea:"Rare Disease",value:[3405220,1108620,9964980,3881360,4090880,1657600]}]

I attempted to use flatmap but did not achieve the expected result

Answer №1

Let's get started:

var data = [
  {category: "Rare Disease", quantity: 3405220},
  {category: "Rare Disease", quantity: 1108620},
  {category: "Rare Disease", quantity: 9964980},
  {category: "Rare Disease", quantity: 3881360},
  {category: "Rare Disease", quantity: 4090880},
  {category: "Rare Disease", quantity: 1657600}
];

var finalResult = Object.values(data.reduce((prev, current) => {
  if (prev[current.category])
    prev[current.category].quantity.push(current.quantity);
  else
    prev[current.category] = { ...current, quantity: [current.quantity] };
  return prev;
}, {}));

console.log(finalResult);

Answer №2

If you want to decrease it

var data = [{type: "Common Ailment", amount: 3405220},
           {type: "Common Ailment", amount: 1108620},
           {type: "Common Ailment", amount: 9964980},
           {type: "Common Ailment", amount: 3881360},
           {type: "Common Ailment", amount: 4090880},
           {type: "Common Ailment", amount: 1657600}]
           
let updatedData = data.reduce((accumulator, { type, amount }) => {
   let entry = accumulator.find(item => item.type === type)
   if (!entry) 
       return [...accumulator, { type, amount: [amount] }];
   entry.amount.push(amount);
   return accumulator;
},[])

console.log(updatedData);

Answer №3

Perhaps you could consider the following approach:

let data = [
  { category: 'Rare Disease', value: 3405220 },
  { category: 'Rare Disease', value: 1108620 },
  { category: 'Rare Disease', value: 9964980 },
  { category: 'Rare Disease', value: 3881360 },
  { category: 'Rare Disease', value: 4090880 },
  { category: 'Rare Disease', value: 1657600 },
];

const groupByCategory = data.reduce((result, item) => {
  result[item.category] = result[item.category] || [];
  result[item.category].push(item.value);
  return result;
}, {});

const transformedArray = Object.keys(groupByCategory).map(category => ({
  category,
  values: groupByCategory[category],
}));

Answer №4

Inserted clarification in the comments. Reference Array.prototype.reduce()

function categorizeByType(data) {
  // Implementing reduce function to iterate over object and create a categorized object
  return data.reduce((acc, item) => {
    // Checking if the type value is already present
    let existing = acc.filter(x => x.type === item.type)[0];
    // If not present, add it to the resulting (accumulator) object
    // Else, append the value to the existing object's value array
    if (!existing) {
      acc.push({
        type: item.type,
        value: [item.value]
      });
    } else {
      existing.value.push(item.value);
    }
    // Returning the resulting object
    return acc;
  }, []); // Using an empty array as the result object
}

var data = [{
  type: "Rare Disease",
  value: 3405220
}, {
  type: "Rare Disease",
  value: 1108620
}, {
  type: "Rare Disease",
  value: 9964980
}, {
  type: "Rare Disease",
  value: 3881360
}, {
  type: "Rare Disease",
  value: 4090880
}, {
  type: "Rare Disease",
  value: 1657600
}];

// Calling the categorizeByType function.
console.log(categorizeByType(data));

Answer №5

const diseases = [{name: "Rare Disease", cases: 3405220},
       {name: "Rare Disease", cases: 1108620},
       {name: "Rare Disease", cases: 9964980},
       {name: "Rare Disease", cases: 3881360},
       {name: "Rare Disease", cases: 4090880},
       {name: "Rare Disease", cases: 1657600}];
let newDiseases = [];
diseases.forEach((item) => {
  if (newDiseases.find(disease => disease.name === item.name)) {
    for (let d of newDiseases) {
        if (d.name === item.name) {
            d.cases.push(item.cases);
        }
    }
  } else {
    newDiseases.push({"name": item.name, "cases": [item.cases]});
  }
});
console.log(newDiseases);

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

The ternary operator is malfunctioning when it comes to the condition

I've encountered an issue while trying to integrate a custom MUI button into my project. My goal is to have the button enabled only when 2 specific objects are not empty, otherwise it should remain disabled. Despite my efforts, the code I've writ ...

Updating a component's value in Angular 6 when there is a change in the corresponding service

My objective sounds straightforward, but I am struggling to implement it: I want one of my components to automatically update when a variable in a service changes. To illustrate my issue, consider the following example: Imagine having a service that incr ...

Using React.js with a PHP backend to create an API ecosystem for

Creating an admin panel for a website with CRUD operations has been quite the journey. I began by setting up API endpoints and hosting them on a subdomain. Fetching data from these endpoints was successful for displaying all contacts (GET), individual cont ...

Converting HTML elements into Vue.js Components

In my Vue.js application, I am utilizing a d3.js plugin to generate a intricate visualization. I am interested in implementing a customized vue directive to the components that were incorporated by the d3 plugin. It seems that the $compile feature, which ...

Trigger callback function when user selects a date on the calendar using Material UI X Date Picker

I am currently utilizing the DateTimePicker component in material ui, version 5. I am looking for a way to intercept the callback triggered when a user clicks on a day in the calendar selector: https://i.stack.imgur.com/0Tlogm.png Although the DateTimePi ...

JavaScript's asynchronous callbacks

As a PHP developer delving into the world of NodeJS, I find myself struggling to fully grasp the concept of asynchrony in JavaScript/Node. Consider this example with ExpressJS: router.get('/:id', function (req, res, next) { var id = req.par ...

GraphQL is not capable of fetching data directly from a mysql database

Trying to incorporate GraphQL with MySQL in a Node.js Express server has been my recent challenge. Unfortunately, every time I execute my query, an error surfaces. Here is the specific error message: { "errors": [ { "message&quo ...

Utilize setState in a ReactJS function within an if statement towards the end

Help needed! I'm facing issues trying to use the function setState within an if statement inside another function. Specifically, I'm working on creating a series of Tab components with inline styles that determine their visibility. Before returni ...

Implementing server authentication with Faye in Node.js

As a complete newbie to node.js and faye, I'm struggling with the basics and not sure what questions to ask. This is how my faye server setup looks like, running on Nodejitsu: var http = require('http'), faye = require('faye' ...

Locate grandchildren elements using getElementById

My task is to modify the content and attributes of the table. The DOM structure is generated by a third-party tool, and I am using JavaScript to make changes in various sections. <div id="myId"> <div> <div> <table&g ...

Encode image into base64 format without the need for file uploads

Is there a way to save an image in localStorage in base64 format without uploading it? I want to convert an existing image into base64. Can someone provide guidance on how to achieve this? function loadImageFileAsURL() { var filesSelected = document ...

How to successfully send data props from child components to parent in Vue3

I am currently working on a personal project to add to my portfolio. The project involves creating a registration site where users can input their personal data, shipping information, and then review everything before submission. To streamline the process ...

Arranging elements on a webpage using Javascript

Creating a Dynamic Div Layout with JavaScript I have successfully implemented functionality wherein clicking on + opens a div and clicking on - closes it. However, I am now faced with the challenge of handling multiple divs at runtime. How can this be ach ...

Do changes in Input fields reflect in the parent component?

I was under the impression that I could share data with child components using @Input() directive and communicate data back to the parent component with @Output() along with the appropriate emit. However, I recently discovered that modifications made to th ...

Activating Dynamic Functionality through JavaScript Input

I am currently working on a form in Apex 4.1 where I have an address lookup field that utilizes JavaScript to connect to an address database and populate separate fields with the address details (address1, address2, town, postcode). On the same page, I ha ...

TypeScript abstract class generics: `Class<?>` type

When working with TypeScript, I often utilize a Java-like type called Class: interface Class<T = void> { new(...args: any[]): T; } Unfortunately, this type doesn't seem to be compatible with abstract classes: abstract class Bar {} class ...

The noclose feature in Twitter Bootstrap is malfunctioning when placed within a div

I have a PHP page named a.php that contains the following code: <ul class="dropdown-menu noclose"> This code functions correctly, preventing the drop-down menu from closing until the user clicks outside the box. However, when I load the entire a.p ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Is a preloader needed in a Vue.js app?

I'm currently exploring the world of Vue.js and could use some advice. When making a GET request using the axios package, I would like to display a preloader for the entire page until all the data has been loaded. While I know this is a common task i ...

Passport.js implementation in a Next.js application does not persist the user's login state when navigating between routes

I'm currently utilizing passport.js with the local-strategy for authentication in my next.js application. Data store requests and authentication are functioning properly. However, I need access to the req.user in another route to retrieve the users._ ...