A Guide To Adding up Values and Assigning Them to Corresponding Objects in Vue

Currently, I'm in the process of creating a computed property that will generate a fresh Array of Objects

The challenge I am facing is figuring out how to sum up the number of values that match a specific value and then insert that value into the corresponding object?

The specific value I want to add is count:. My goal is to count the number of objects that correspond to each status value in every workflow object from a separate array named engagements.

In order to showcase what the Array should look like after the computation, take a look below:

var arr = [
  { workflow_id: 1, 
       statuses: [ 
                  { status: "Received", count: 3},
                  { status: "Review", count: 2},
                  { status: "complete", count: 4}
                ] 
  },
  { workflow_id: 2, 
       statuses: [ 
                  { status: "Received", count: 3},
                  { status: "Review", count: 1},
                  { status: "complete", count: 1}
                ] 
  },
  { workflow_id: 3, 
       statuses: [ 
                  { status: "Received", count: 3},
                  { status: "Data Entry", count: 2},
                  { status: "complete", count: 1}
                ] 
  },
]

If anyone has any suggestions or can guide me towards a solution for this problem, it would be greatly appreciated! Thanks!

Answer №1

To achieve the desired outcome, it is necessary to utilize Array#reduce on the statuses within each iteration in order to create a new array of statuses without mutating the original. Additionally, you can use Array#filter to iterate through the engagements and tally those that match both the workflow_id and status.

const workflows = [{
    id: 1,
    workflow: 'bookeeping',
    statuses: [{
        status: 'Received'
      },
      {
        status: 'Prepare'
      },
      {
        status: 'Review'
      },
      {
        status: 'Complete'
      },
    ]
  },
  {
    id: 2,
    workflow: 'payroll',
    statuses: [{
        status: 'Received'
      },
      {
        status: 'Scan'
      },
      {
        status: 'Enter Data'
      },
      {
        status: 'Review'
      },
      {
        status: 'Complete'
      },
    ]
  },
  {
    id: 3,
    workflow: 'tax preparation',
    statuses: [{
        status: 'Received'
      },
      {
        status: 'Scan'
      },
      {
        status: 'Prep'
      },
      {
        status: 'Review'
      },
      {
        status: 'Complete'
      },
    ]
  },
];
const engagements = [{
    engagement: '1040',
    workflow_id: 1,
    status: 'Received'
  },
  ...
];

const res = workflows.map(({statuses, id}) => ({
  workflow_id: id,
  statuses: statuses.reduce((acc, cur) => {

    const count = engagements.filter(({workflow_id, status}) => workflow_id === id && status === cur.status).length;
    
    if(count === 0) return acc;

    acc.push({status: cur.status, count});

    return acc;
    
  }, [])
}))

console.log(res);

Answer №2

Take a look at this code and analyze it!

function calculateTotals(data) {
  const totals = [];
  
  for(const item of data) {
    const existingItem = totals.find(e => e.id === item.id);
    
    if (!existingItem) {
      totals.push({
        id: item.id,
        values: [{
          value: item.value,
          count: 1
        }]
      });
      continue;
    }
    
    const value = existingItem.values.find(v => v.value === item.value);
    
    if (!value) {
      existingItem.values.push({
        value: item.value,
        count: 1
      });
      continue;
    }
    
    value.count += 1;
  }
  
  return totals;
}

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

Webpack returns an undefined error when attempting to add a JavaScript library

I am a newcomer to webpack and I am attempting to incorporate skrollr.js into my webpack setup so that I can use it as needed. However, I am unsure of the correct approach for this. After some research, I have found that I can either use an alias or export ...

I encountered an issue where my button's onClick function was not functioning properly with the clickable component

Here is my display I have a component(Product) that can be clicked. One of its children is also a button. However, when I click it, the Product's function runs. How can I make sure my button executes separately? <ProductForm> ...

Step-by-step guide on redirecting a page using AJAX while also sending data to a controller

Is it possible to redirect to another page after a successful action, but not able to retrieve the data that was passed? Here is the jQuery code: $.ajax({ type:'GET', url:link, data:data, success:functio ...

Generating ChartJS in Real-time

I have a straightforward form where the user selects a start date and an end date. Once these dates are selected, the tool automatically fetches data from a website in JSON format. Below is the code for my Angular controller: (function () { angular.m ...

Can you combine multiple user validation rules with express-validator?

I have a set of rules that are almost similar, except for one where the parameter is optional and the other where it is mandatory. I need to consolidate them so that I can interchangeably use a single code for both cases. Is there a way to merge these rul ...

Timeout set to run indefinitely

Looking at the code snippet below, it seems to be running at a frame rate of 60 frames per second. If any button is clicked, the variable isjump will be set to true and the following code will start executing. The goal here is to exit the jump() function a ...

Using JavaScript to create temporary drawings on a webpage that automatically erase themselves

I am curious about how to achieve a scribble effect that self-erases, similar to what is seen on this website: Example: Thank you! I have come across some similar scripts, but I am struggling to understand how to make the scribble disappear after a few ...

How can you turn consecutive if statements into asynchronous functions in JavaScript?

In my code, I have a loop with a series of if statements structured like this: for( var i = 0; i < results_list.length; i++){ find = await results_list[i]; //result 1 if (find.Process == "one") { await stored_proc(38, find.Num, find ...

How to invoke a function from a different ng-app in AngularJS

I have 2 ng-app block on the same page. One is for listing items and the other one is for inserting them. I am trying to call the listing function after I finish inserting, but so far I haven't been successful in doing so. I have researched how to cal ...

"Encountering an issue with Multer where req.file is displaying as undefined in NodeJS

Recently, I followed the advice of several YouTubers and used multer for file upload in my project. However, despite correctly defining all the functions, req.file always appears as undefined. booking_route.js const express = require('express'); ...

Setting up CloudKitJS Server-to-Server Communication

I'm struggling to make this work. I keep encountering the following error message: [Error: No key provided to sign] Below is my configuration code: CloudKit.configure({ services: { fetch: fetch }, containers: [{ containerIdentifier: & ...

Implementing dynamic data binding in JavaScript templates

I've been experimenting with jQuery and templates, and I managed to create a basic template binding system: <script type="text/template" id="Template"> <div>{0}</div> </script> Furthermore... var buffer = ''; v ...

Sorting arrays in Typescript

Is there a way to alphabetically sort an array of objects in Typescript based on a specific field? The array I have currently looks like this - https://i.stack.imgur.com/fQ3PA.png I'm interested in sorting it alphabetically by the 'channel' ...

Efficiently importing SCSS files into Vue single file components using Webpack without redundancy

Encountering a problem with my Vue SFCs where accessing a scss file results in duplicated styles leading to large css bundles and crashing Dev Tools during style debugging. Using Webpack 4 and webpack-dev-server for development services with hot reload, w ...

Utilizing Shadow Root and Native Web Components for Seamless In-Page Linking

An illustration of this issue is the <foot-note> custom web component that was developed for my new website, fanaro.io. Normally, in-page linking involves assigning an id to a specific element and then using an <a> with href="#id_name&quo ...

"What are some strategies for locating a specific item within a MongoDB database, or perhaps querying for all

I am currently searching for a specific item using the following code: Product.find({ category: "bracelet" }); In one scenario, I need to find items with any category value or simply search for all items like this: let cat; if (req.body.cat) ...

Utilize Laravel collection to group items in a nested array based on a specific criterion

My code is designed to handle an array with the variable name $array. Here's a sample of how this array looks: $array = [ "data"=> [ [ "company"=>[ "id"=> 1, "name"=> "company1" ...

Is there a way to ensure a dialog box is positioned in the center of the window?

After adjusting the dimensions of my jQuery UI dialog box with the following code: height: $(window).height(), width: $(window).width(), I noticed that it is no longer centered on the window. Do you have any suggestions on how I can recenter it? ...

Display resize grip when hovering

Is there a way to make elements resizable using resize: both, but only show the corner handle when hovering over the element? https://i.sstatic.net/cGIYf.png I am looking for a solution to display that specific handle only on hover. ...

Incorporate a JavaScript form into a controller in MVC4

I'm facing an issue where I need to trigger a JavaScript function from within a controller method in my project. Here is the code snippet that I am using: Public Function redirectTo() As JavaScriptResult Return JavaScript("ToSignUp()") E ...