Organize values based on tasks and store progress in an array format

My goal is to categorize tasks based on their descriptions in order to calculate the average progress of each task later.

    let ar = [
  [
    { task: 'Hello world', c: 56 },
    { task: 'Hello world1', c: 34 },
    { task: 'Hello world2', c: 80 },
    { task: 'Hello world3', c: 80 },
  ],
  [
    { task: 'Hello world', c: 12 },
    { task: 'Hello world1', c: 60 },
    { task: 'Hello world2', c: 90 },
  ],
];
let t = [
  { task: 'Hello world', c: [56, 12] },
  { task: 'Hello world1', c: [34, 60] },
  { task: 'Hello world2', c: [80, 90] },
  { task: 'Hello world3', c: [80] },
];

ar represents the original data and t is the desired outcome I am aiming for.

Appreciate your help

Answer №1

To group elements based on the task value, one can utilize the Array.prototype.reduce method.

Additionally, by using Array.prototype.flat, it is possible to generate a 1d array containing all elements from sub-arrays concatenated together.

let input = [
  [
    { task: 'Hello world', c: 56 },
    { task: 'Hello world1', c: 34 },
    { task: 'Hello world2', c: 80 },
    { task: 'Hello world3', c: 80 },
  ],
  [
    { task: 'Hello world', c: 12 },
    { task: 'Hello world1', c: 60 },
    { task: 'Hello world2', c: 90 },
  ],
];

const groupBy = input.flat().reduce((acc, cur) => {
  acc[cur.task] ? acc[cur.task].c.push(cur.c) : acc[cur.task] = {
    task: cur.task,
    c: [ cur.c ]
  };
  return acc;
}, {});
const output = Object.values(groupBy);
console.log(output);

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 could be causing this `even` function to malfunction when utilizing getElementById?

Need assistance with utilizing document.getElementById? Let's take a look at this code snippet: function even() for (i = 0; i < 10; i++) { if (i % 2 == 0) { alert(i); } } document.getElementById("even").innerHTML = i + &apos ...

what is the method to incorporate an array of objects in a schemaless mongoose database?

**model schema** var mongoose = require('mongoose'); var Schema = mongoose.Schema; var itemSchema = new Schema({ name: {type: String, required: true}, price: {type: String} }); var objectSchema = new Schema({ name: {type: String, req ...

Issues encountered with the performance of a Laravel Vue.js application

I am encountering a recurring issue when trying to run new applications that combine Laravel with Vue.js. This problem persists whether I am working on a partially developed app or starting from scratch with a fresh Laravel installation. Upon setting up La ...

What is the correct way to utilize JSON with AJAX?

I am looking to transfer data from a php backend to a browser using JSON. I have a basic understanding of the process and have included an example code snippet below. However, I have been advised that this may not be the most efficient approach. Due to my ...

Accessing geolocation on a mobile web browser: A step-by-step guide

I have implemented HTML5 geolocation functionality using code I found in the documentation: getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(this.showPosition, this.showError); } else { alert("Geoloc ...

What causes the discrepancy in results between Javascript sha1 and PHP5 sha1 when generating hashes for utf-8 strings?

I'm facing an issue with utf-8 characters in a string. The PHP sha1 and Javascript sha1 are generating different codes for the same string "abc艾". Can anyone assist me with this? Thank you in advance. PHP code: $str = "abc艾"; $result = sha1($st ...

Navigating the Basics: Understanding the Four Quadrant Selection Grid in a Material UI & React Pop-Up Form

Sorry if these questions seem silly. I'm diving into React & Material-UI without a mentor to guide me, relying on documentation and tutorials. Is there a better place for quick beginner questions? Maybe a chat forum or Slack group? Not sure if Stack i ...

Received undefined response from Axios.get() request

While working with the code below, I encountered an issue. The axios get request from await axios.get('/products/api') is functioning properly and I can see the data in the console. However, for await axios.get('/users/api'), 'Unde ...

Error message: The call stack size has surpassed the limit, resulting in a RangeError. This issue is

I currently have a dynamic unordered list within my HTML file. Upon loading the page, certain list items are automatically added. The original format of the list is displayed as follows: <ul class="ui-front"> <li><div>1</div& ...

Using jQuery to show an Ajax loader while the page is loading

Is it possible to display a loader (gif) before the HTML is loaded and during a page transition? I have seen this type of effect on many websites and am curious if it can be implemented. If so, is it achievable using jQuery, AJAX, and PHP? I know how to ...

Obtaining the variable from the exec function in Node.js can be achieved by capturing

I am trying to access the values of variables w1 and h1 outside of the exec function and display them using console.log. exec(command, function(err, stdout, stderr) { var resolution = stdout.split("x"); w1 = resolution[0]; h1 = resolution[1]; ...

It appears that the fetch operation does not wait as expected

Having some trouble with a caching system in my code where I'm trying to load the same template quickly. Even though I've tried implementing a basic caching mechanism to only fetch the template if it hasn't been loaded before, I'm strug ...

Issues with the functionality of Google Translate's JavaScript code snippet are causing

After trying out the code snippet provided on w3schools.com, I encountered a discrepancy between the results displayed on the website and those on my personal computer. <div id="google_translate_element"></div> <script> function googleT ...

Parsing a JSON file containing multidimensional arrays on each line using R

In my possession is a json file with 585 nested arrays, each structured as follows: [["12345678", [["12345678912345678", "dummy tweet #hashtag", "2015-05-20 15:33:11", "en"], ["12345678123456781", "dummy tweet again", "2015-05-18 22:08:30", "en"]]] Every ...

Developing a web application using Node.js and Angular that can send both 401 Unauthorized and 200 OK responses

Upon clicking the register button on my form, it appears that Angular is setting the URL to /profile (a protected route) before the node server can authorize the JWT and send the 200 OK response. I'm unsure of how to address this issue. Even when I h ...

Discovering elements using Selenium in a JavaScript popup box

The issue at hand is rather straightforward. I am faced with the task of clicking on an element within a popup that has been dynamically generated by JavaScript code. The challenge arises as the page is solely accessible in Internet Explorer and the elemen ...

Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of t ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

What is the best way to combine key-value pairs objects into a single object using JavaScript?

I am faced with the challenge of creating a new object that combines keys from a specific array (const props = []) and values from existing objects. If a key does not exist in an object, I aim to populate it with null or placeholder values. Here is my cur ...

Is it possible to access the Firebase user object beyond the confines of the Firebase function?

Despite successfully logging users into my application using Google Auth from Firebase, I am facing an issue where the User object does not display on the front end of my application (which utilizes Pug templates). How can I resolve this? The code snippet ...