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

Transition from mouse wheel scroll to page scroll not functioning properly when overflow is enabled

The website has a fixed element that uses overflow:auto. Users can scroll this element by positioning the mouse over it. However, once the element reaches the end of its scroll, the page does not seamlessly take over the scrolling. Instead, there is about ...

Ways to speed up the disappearance of error messages

There is a minor issue that I find quite annoying. The validation error message takes too long (approximately 3 seconds) to disappear after a valid input has been entered. Let me give you an example. Do you have any tips or tricks to resolve this problem? ...

What is the best way to generate a live map with constantly updating markers?

Is it possible for me to learn how to develop a live map similar to the one on this site: www.lightningmaps.org? It's fascinating to watch new markers pop up every few seconds. I'm interested in building a real-time map that can track IP locatio ...

Styling the Menu Item with CSS

A graphic designer provided me with these elements to incorporate into the HTML design. Everything was going smoothly until I encountered the faint, uneven borders on the LI tags, especially when dealing with a list containing only five items. If anyone ...

Using NestJS to inject a Factory provider into another Factory

I've gone through various questions here, but none of them addressed my issue: NestJS - Inject factory provider into another provider doesn't work I'm trying to set up an async provider that retrieves configurations from a remote repositor ...

Using Ajax with Laravel for Beginners

After clicking a button in my Laravel app, I want to update some data in the database using ajax without reloading the page. This is a simple ajax request where only a function in a controller needs to be invoked. I tried setting up the ajax request follo ...

How can you include a comma between two objects within a string, excluding the last object, using JavaScript?

I have a string object stored in a variable passed from another class. My question is how can I add a comma between two objects, excluding the last object? Below is my code snippet: { "id":"57e4d12e53a5a", "body":"asdas", "publishe ...

What is the subclass of all object literal types in TypeScript?

With the `strictFunctionTypes` setting turned on, function parameters are checked contravariantly. interface Func<T> { (p: T): unknown } declare let b: Func<{p1: string}> declare let c: Func<{p2: number}> declare let d: Func<{p3: nu ...

Problem: The variable "$" is not defined in angular datatables causing a ReferenceError

Trying to implement Paging and sorting in my table, but encountered an error even after following all the steps mentioned here: . Tried troubleshooting the issue with no success. Ensured that all dependencies were installed properly. Below is the compo ...

dynamically open ngx-bootstrap accordion panels

I implemented the ngx-bootstrap accordion feature to display a list of blog posts. Below is the template structure: <accordion id="blog-list"> <accordion-group *ngFor="let post of posts; let first = first;" [isOpen]="first" id="post-{{post.i ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

Euler 13: Surprising outcome when attempting to combine several String variables

I'm currently working on a challenging problem found on euler: here Large sum Problem 13 In this problem, the task is to determine the first ten digits of the total sum when adding up one-hundred 50-digit numbers. 37107287533902102798797998220837590 ...

Choose the initial selection from a dropdown menu using AngularJS

I am facing a minor issue where I want the first element in my select dropdown to be displayed properly rather than just a blank space. Below is the code snippet I am currently working with: <select style="border-radius: 4px;" class="form-control" ng- ...

Ways to transfer a jQuery variable value to a PHP variable

I am trying to transfer a jQuery variable value to a PHP variable on the same page using AJAX in my JavaScript code. I have attempted to print the PHP variable but encountered an error. Any assistance would be greatly appreciated. <script type="text/ ...

Tips for dividing an array based on a defined regex pattern in JavaScript

I want to split a string of text into an array of sentences while preserving the punctuation marks. var text = 'This is the first sentence. This is another sentence! This is a question?' var splitText = text.split(/\b(?<=[.!?])/); split ...

Navigating the art of employing different fonts for a website

I am looking to incorporate the trainway font into my website, but I'm concerned that the user may not have it installed on their device. Is there a way to showcase text in a specific font without requiring the user to download and install it? Thank ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Remove the most recent file in a MongoDB collection using a DELETE request

As I delve into the world of REST APIs, one task on my to-do list is to delete the last POST in my mongoDB collection using a DELETE route with mongoose. Despite searching for answers, none seem to provide guidance on achieving this deletion through a rout ...

Why is Puppeteer failing to download to the designated folder using "Page.setDownloadBehavior" in Windows?

When trying to download a file using Puppeteer, I found that the code works perfectly on a Mac OS machine but fails on a Windows machine. The code snippet I used is shown below: await page._client.send( 'Page.setDownloadBehavior', { beha ...