Combining information once constructing a complex array structure in JavaScript

My reduce function is successfully building multiple levels of data, but I have encountered an issue. Currently, it organizes the data by employee first, then by date, area, and job. While all the data is displayed correctly at each level, I am now attempting to aggregate specific data for a totals section at the date level.

The problem arises when I try to calculate the total number of scans for orders on a particular date. Instead of aggregating the values, it simply lists them individually. To address this issue, I want to create a new value called "total_scans" that sums up all scans for any orders placed on that date.

In the code snippet below, my goal is to update the total_scans value so that it correctly reflects the sum of scans for all orders on a given date. For instance, for Miranda's record on 8/12, the total_scans at the date level should be 49. Am I moving in the right direction?

Answer №1

Your implementation of the reduce function seems a bit unusual. The purpose of using reduce is to consolidate an iterable (such as an array) into a single value, typically a String or Number.

Furthermore, by making changes directly to objects and arrays within your reducer, you are introducing unintended side effects. Since JavaScript passes arrays and objects by reference, any modifications made will affect the original data object, which goes against Vue's recommended practices. If you need to alter data, consider using a watch instead of a computed.

Additionally, it appears that your reduce function may be overly complex. Instead of a lengthy reduce operation, you could simplify it as shown below, with an initial value of 0:

const nest = (rows) =>
  rows.reduce(
    (sum, row) => {
       return sum + row['scans'];          
    },
    0
  );

This code snippet calculates the total number of scans. If you only want to count scans based on a specific date, you can optimize the process by filtering the array first. Consider something like this:

const nest = (rows) => 
  rows.filter(({job_date}) => job_date === SomeDate).reduce(...)

The {job_date} represents a destructuring assignment syntax. You could also create a separate computed property for the filtered dates array.

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

A guide on passing ObjectID using Ajax to the backend in Node.js

I am trying to create a delete button using font-end code (HTML, Javascript) but I am facing an issue with sending ObjectID via ajax var retName = $(this).data("row-id"); $.ajax({ type: "POST", url: "/delete", data: ...

Using the <noscript> tag for an individual element or a comparable alternative

So, I have a link labeled "Impressum" that when clicked, opens up the Impressum section. <a data-open="something">Impressum</a> <div class="reveal" id="something" data-reveal> <img src="images/reverseLogo.png"> <h1>Imp ...

Access the value of a specific field within an object using ng-options and use it to filter out other

I have created two separate lists. 1) The first list contains the service names. 2) The second list contains the product names assigned to each service name. Each product has a unique ID that matches it with its corresponding service. app.controller( ...

The asynchronous `beforeEach` function in the router activates two different

I'm facing an issue where two routes are being triggered when I'm trying to wait for an asynchronous response in my route guard. The problem arises when the page loads, with the "/" route being hit instantly followed by the targeted route. router ...

Ways to rejuvenate an angular component

I am in the process of developing a mobile application using ionic 4. The app supports two languages, namely ar and en. The menu drawer is a pre-built component included within the app. In order to ensure that the drawer component displays the correct sty ...

Limiting the scope of the jQuery scrollToFixed functionality within various nested DIV elements

I have been grappling with this issue for the past two days without success. I am utilizing the ScrollToFixed plugin from https://github.com/bigspotteddog/ScrollToFixed and my goal is to restrict the fixed positioning within a parent DIV. Despite scouring ...

Extract the href value from an element and append it to the src attribute of an image

How can I extract the href link from the .image1 div class? <div class="image1"> <a href="/images/productA.jpg"> </a> </div> Then, how do I insert it into the image src shown below? <ul class="example"> <li class ...

Error message: "When using Webpack 4 with Bootstrap, a TypeError occurs where property 'jquery' is read as undefined."

I've recently delved into the world of webpack and everything seems to be running smoothly. However, when I run my webpack app, I encounter the following error within Bootstrap: var version = $.fn.jquery.split(' ')[0].split('.'); ...

Obtaining Function Call Results by Querying Node.js MySQL Connection

One issue I'm encountering while trying to retrieve data from a database is the synchronization of calls. In my attempt to resolve this problem, I experimented with a demo example and used callback functions. Being relatively new to node.js, I am unce ...

When attempting to send an email using the emailjs.send function, an unexpected error occurred showing the URL https://api.emailjs.com/api/v1.0/email/send with a

import emailjs from 'emailjs-com'; async function sendEmail() { try { const serviceID = '...'; const templateID = '...'; const userID = '...'; const emailParams = { to_email: '...&a ...

Is there a way to make the button text bold before deleting it post clicking on an alert message?

While testing my sequence in IE, I noticed that it appeared correctly, but in Chrome, the button text was not showing up as bold. Instead, only the alert message was displayed, and the button itself was removed. Upon further investigation using Chrome&apo ...

Next.js endeavors to interpret MDX files as basic JavaScript code

Currently, I'm in the process of creating a website using Next.js and incorporating (local) MDX files for my content. However, I've encountered an issue where whenever I add a .MDX file to my source tree and attempt to navigate to it, Next.js thr ...

Discovering the quantity of arguments passed into a constructor in Node.js

In my Node.js code, I have a constructor that looks like this: function Tree() { //Redirect to other functions depending on the number of arguments passed. } I then created instances of objects like so: var theTree = new Tree('Redwood'); var ...

In TypeScript, what is the method to specifically retrieve only resolved Promises while disregarding errors?

I have come up with a function that is supposed to take an array of Promises and only return the resolved ones while ignoring any errors. It's similar to Promise.all but without considering errors. The challenge is implementing this function correctly ...

Encountering a 500 error when making API requests after deploying Next.js on Vercel, although they work fine

I recently deployed my Next.js app to Vercel, and I'm experiencing issues with my API calls returning a 500 status code, even though they work perfectly fine on localhost. The initial load using getStaticProps seems to be working, so I suspect the con ...

Revitalize website when submitting in React.js

I need assistance with reloading my React.js page after clicking the submit button. The purpose of this is to update the displayed data by fetching new entries from the database. import React, {useEffect, useState} from 'react'; import axios from ...

Is it possible to employ a jQuery handler as the selector for the .on() method?

Can a jQuery handler $(...) be used as the selector for .on()? The code snippet below illustrates this: how can I change the circle's color to blue without having a plain text representation of my selector, but still using a handler? // This works. ...

Please refrain from including HTML code within the div element

When I input the following text inside a textarea: <strong>test</strong> and then display it within a div, the text appears in bold instead of showing the HTML code as entered. How can I prevent the HTML code from being rendered and instead d ...

Challenges with downloading a file synchronously using NodeJS

Having trouble with writing files synchronously in my local application using the 'download-file-sync' module. When I use 'writeFileSync', the file size doubles even though the content seems to be identical to a file downloaded through ...

Storing a blank field in a Kendo grid

Is there a way to clear the content of a cell and save it as an empty field? I attempted to specify my field in the parameter update map using the following code: ((data.Value) ? '","Value": "' + data.Value : "") + and in the schema like this: ...