How to utilize the reduce method with an array of objects in JavaScript

Every week, a number of objects are delivered to me. Each object contains information such as date, hours, and other fields. I need to arrange these objects in an array based on the total hours for each day.

Here is an example of the objects:

var anArray = [{
  'End':"22:00",
  'Id':"Q45575",
  'Name':"W-299849",
  'Start':"20:00",
  'date':"2018-02-04",
  'hours':2
},{
  'End':"21:00",
  'Id':"Q45551",
  'Name':"W-299809",
  'Start':"15:00",
  'date':"2018-02-07",
  'hours':5
},{
  'End':"20:00",
  'Id':"Q45515",
  'Name':"W-299849",
  'Start':"10:00",
  'date':"2018-02-04 ",
  'hours':2
}];

The desired output should be something like this (assuming Sunday is 2/4):

Sun Mon Tue Wed Thu Fri Sat

4 0 0 5 0 0

This is what I have currently:

var resourceData = data.reduce((a, c) => {
var targetDay = new Date(c.date).getDay() === 6 ? 0 : (new Date(c.date).getDay() + 1);
if (a) {
  a['week'][targetDay] += c.hours;
} else {
  a = { 'week': new Array(7).fill(0) };
  a['week'][targetDay] = c.hours;
}
return a;
}, {});

Unfortunately, it's not working as expected and I'm encountering errors with the variable targetDay.

Answer №1

Instead of diminishing, I believe that using forEach would be a more suitable approach.

See the example provided below.

var anArray = [{
  'End':"22:00",
  'Id':"Q45575",
  'Name':"W-299849",
  'Start':"20:00",
  'date':"2018-02-04",
  'hours':2
},{
  'End':"21:00",
  'Id':"Q45551",
  'Name':"W-299809",
  'Start':"15:00",
  'date':"2018-02-07",
  'hours':5
},{
  'End':"20:00",
  'Id':"Q45515",
  'Name':"W-299849",
  'Start':"10:00",
  'date':"2018-02-04",
  'hours':2
}];

var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

var result = {};

//initialize each day with zero hours
(new Array(7).fill(0)).map((x,ix) => { 
  result[days[ix]] = 0;
});

//calculate total hours per day
anArray.forEach((d) => {
  var dt = new Date(d.date);
  result[days[dt.getDay()]] += d.hours;
});

console.log(result);

Answer №2

Your code is so close to being finished.

Instead of comparing with if(a) in the reduce handler, you can set initialValue as { 'week': new Array(7).fill(0) }.

Take a look at the comments below:

var anArray = [{  'End':"22:00",  'Id':"Q45575",  'Name':"W-299849",  'Start':"20:00",  'date':"2018-02-04",  'hours':2},{  'End':"21:00",  'Id':"Q45551",  'Name':"W-299809",  'Start':"15:00",  'date':"2018-02-07",  'hours':5},{  'End':"20:00",  'Id':"Q45515",  'Name':"W-299849",  'Start':"10:00",  'date':"2018-02-04",  'hours':2}];

var resourceData = anArray.reduce((a, c) => {
  var targetDay = new Date(c.date).getDay() === 6 ? 0 : (new Date(c.date).getDay() + 1);
  a['week'][targetDay] += c.hours;

  /*
  else {
    a = { 'week': new Array(7).fill(0) };
    a['week'][targetDay] = c.hours;
  }*/ // The else block can be removed since [var a] was created by the initialValue
  return a;
}, { 'week': new Array(7).fill(0) }); // Start with the expected object instead of {}

console.log(resourceData)

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 specified height for input[type=button] in Firefox/Safari is adjusted by subtracting the padding and border

When implementing the following CSS: input[type=button] { background-color: white; border: 1px solid black; font-size: 15px; height: 20px; padding: 7px; } along with this HTML: <input type="button" value="Foo" /> I anticipate that the t ...

Adjusting the Materui LinearProgressWithLabel progress value to reflect a custom value

Is it possible to update the progress value of Material UI's LinearProgressWithLabel component with a custom value instead of the default one? I am trying to achieve this by obtaining my desired value from the upload progress in the Axios.post method, ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

scope.$digest completes before triggering scope.$watch in Karma unit tests

I am interested in testing this specific directive: .directive('uniqueDirective', function () { return { restrict: 'A', scope: { uniqueDirective: '@', tooltip: '@', placement: '@&apo ...

Node.js VAR DeclarationIn the world of Node.js, we make

I am currently expanding my knowledge on Node.js. I came across a line in my book that has sparked my curiosity, and I wanted to seek some clarification. The specific line in question is: var user = req.user = users[req.params.name]; After doing some re ...

PHP/AJAX user action history manager

Is there a library available that offers undo/redo functionality with a complete history for a web application? One possible solution could be a system using php/javascript/ajax where you can record the opposite action and variable state for each user acti ...

Improving mongo information using angularjs

Have an Angular and MongoDB application. This is a part of my API where I have POST and PUT requests. The POST request works fine, but when I send a PUT request, I get an error "Cannot set property 'typelocal' of undefined". However, the PUT requ ...

What are the steps to run a webpack project without relying on webpack-dev-server?

I've been working on hosting my project on GitHub pages by creating a /doc file and placing all my HTML, CSS, and JS there. If you're interested, you can check out my project here: https://github.com/mattfrancis888/the_movie_db The only way I&a ...

Encountering an error in React when attempting to convert a class component to a function

As I've been converting my class components to functions, I encountered a hook error related to my export default. Although I believe it's a simple issue, I can't seem to find the solution I need. The following code is where the error occur ...

Tips for excluding files in a webpack configuration for a Vue application during the production build

I am attempting to remove an Html file named "dev.html" from the final product build. What configurations do I need to make in webpack for this? I understand that rules need to be applied, but where exactly do I need to configure them? Below is a snippe ...

What steps can I take to ensure a website designed for Firefox will work seamlessly on Safari and Chrome browsers as well?

As someone who is still learning about web development, I find myself struggling with browser compatibility issues. It's frustrating to see my website looking different in Chrome compared to Safari. While I know that browsers interpret code differentl ...

Avoiding Duplicate Form Submissions Without JavaScript

Currently, I am working on a project where I am implementing the MVC pattern. Upon successful submission of a form, I redirect the user and display a flash message indicating success using session data. Users face no issues when using the back button or re ...

What is the inability to place a div that is 30% wide alongside another div that is 70% wide, and keep them in a horizontal line?

If I make a div that is 30% wide, and another div that is 70% wide, they do not align horizontally. To fix this, I need to ensure that the combined widths of the two divs are less than 100%. Here's an example of how it can be done: <div id="wrapp ...

What's the Reason Behind the Ineffectiveness of Footer Background Color in HTML CSS3?

Having some trouble setting the background color for my footer to something other than white. I've been able to successfully change the background of other layout elements, but the footer is giving me issues. Check out the code below: <footer> ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Saving the object returned by the useRef hook into the Redux state

I have a question. I am developing a music platform similar to Spotify using Next.js. To manage states, I am utilizing Redux Toolkit. In order to play music, I have integrated the audio element within a component that includes controls to adjust the music ...

Issue (@websanova/vue-auth): http plugin has not been properly configured in drivers/http/axios.js

I've been working on integrating vue-auth into my laravel-vue application, but I'm encountering some console errors: Error (@websanova/vue-auth): drivers/http/axios.js: http plugin has not been set. Uncaught TypeError: this.plugins.http is u ...

Using the quote and saying "quotation marks"

Any ideas on how to approach this? This is driving me crazy: $toReturn .= " function addProd(pExists) { document.getElementById('products').innerHTML = \"<tr><td id='prod_n'><input type='text&apos ...

Using SVG files as properties in React from a data.js file

I have a website where I store my content in a data.js file and pass it to my components using props. Everything is working correctly, except for my .svg files. When I try to display them, they do not appear. However, if I change the extension of the image ...

Unusual syntax in Symfony framework

I am currently working on a new project for a website using the Symfony3 framework, and I have encountered an issue with understanding the syntax in Twig: <li><a href="{{ path('contact') }}">{{ 'site.template.menu.contact'| ...