Create an object name in an Angular factory or service by utilizing the initial and final dates contained within an array

I have a method in my Angular service/factory that accepts an array of arrays containing objects [[{},{}],[{},{}]] as a parameter.

The parameter structure consists of arrays representing weeks, with each day's object containing a date and an integer value. For example, {"2017-01-10": 711}.

The goal of the method is to combine each week's data into a single object while summing up the integer values. For instance,

{"name": "Week 1", "total": 3228}

How can I generate a name/label by extracting the first and last elements of each week array? This would result in an output like:

{"name": "Week 1 - 2017-01-10 to 2017-01-15", "total": 3228}

Below is the sample input passed to the method:

[
   [
      {
         "2016-11-01": 319
      },
      {
         "2016-11-02": 782
      },
      ...
   ],
   [
      {
         "2016-11-07": 319
      },
      {
         "2016-11-08": 782
      },
      ...
   ]
]

Here is the JavaScript method implementation:

function assignWeekNamesAndTotals(arrayOfWeeks) {

    var data = arrayOfWeeks;

    var result = data.reduce(function (previous, current, index) {

        var total = current.reduce(function (sum, object) {
            for (var key in object) {
                sum += object[key]; // calculate total
            }
            return sum;
        }, 0);

        // Format the object as needed
        var temp = {};
        temp.name = "Week " + (index + 1);
        temp.total = total;

        previous.push(temp);
        return previous;
    }, [])

    console.log("Assign Week names and Totals Output: " + JSON.stringify(result, null, "   "));
    return result;   
}

Your help and advice on this matter are greatly appreciated!

Answer №1

My solution involved creating an array of dates:

To achieve this, I implemented a method within my existing method that generates an array containing the dates. The first and last elements of this array were then used to define the period.

function assignWeekNamesAndTotals(arrayOfWeeks) {

    var data = arrayOfWeeks;

    var result = data.reduce(function (previousValue, currentValue, currentIndex) {

        var dateArray = [];

        var createDateArray = currentValue.forEach(function (object) {

            var dateFromObject = Object.keys(object)[0];

            dateArray.push(dateFromObject);

            return dateArray;
        });

        var total = currentValue.reduce(function (accumulator, object) {

            for (var key in object) {
                accumulator += object[key]; // calculate total
            }
            return accumulator;
        }, 0);

        // Customize the output format as needed
        var temp = {};
        var firstDate = dateArray[0];
        var lastDate = dateArray[dateArray.length - 1]
        temp.name = "Week: from " + firstDate + " to " + lastDate;
        temp.total = total;

        previousValue.push(temp)
        return previousValue;
    }, [])
    console.log("Assign Week names and Totals Output (Step 2: " + JSON.stringify(result, null, "   "));
    return result;
}

Here is the resulting output:

[
   {
      "name": "Week: from 2017-01-10 to 2017-01-15",
      "total": 3228
   },
   {
      "name": "Week: from 2017-01-16 to 2017-01-16",
      "total": 363
   }
]

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 modal is not displayed when the on click listener is triggered

I'm a beginner in the world of programming and I'm currently working on creating modals that pop up when clicked. However, I'm facing an issue where the pop-up message doesn't appear when I click the button. Oddly enough, only the overl ...

Tips for transferring form element values to the ajax success callback function?

In my current project, I have implemented a system where multiple dynamic forms are submitted via ajax. The code I am using is as follows: $(document).on('submit', 'form', function (e) { $.ajax({ type: 'post', ...

Launching Stealthy Slider

I am currently having an issue with implementing Sly Slider on a free WordPress theme. I have properly enqueued the JS file, set up the HTML markup, and written a jQuery function following the documentation but it does not seem to work vertically. What cou ...

Halt the submission process by preventing the default action

I need help understanding why preventDefault is not working in this code. I'm struggling with the syntax and would appreciate any assistance The alerts are functioning properly, but preventDefault isn't stopping the submission of the form even t ...

Tips on implementing a Javascript function triggered by a user's click within the video player frame

<script> function greet() { alert("hello"); } </script> <iframe width="100%" height="315" src="https://www.youtube.com/embed/AGM0ibP1MRc" onclick="greet()"></iframe> .Kindly assist me, please. ...

Is it detrimental to have an excessive amount of simultaneous AJAX connections?

In the process of developing a JavaScript based application of significant size, I frequently encounter situations where up to eight (8) AJAX requests are initiated concurrently. In older browsers such as IE6, this can result in certain requests being term ...

Issue with AngularJS ngGrid rendering incorrect page size and malfunctioning pagination

I'm currently working on implementing ngGrid data pagination for some data retrieved from a service. The table displays correctly and the search filter is functional. However, despite setting the pageSize in my pagingOptions to 25, the table shows all ...

Parenting and Child Components: Keeping the State in Sync

I am currently diving into my initial React project which focuses on a basic expense tracker for credit cards. While I'm still in the learning phase, I hope you can decipher the intent behind my code. My current roadblock involves mapping the state an ...

Having trouble with deploying Node.js to Heroku? Feel like your 'git push her

After successfully running my app locally, I encountered an issue when trying to deploy it to Heroku. The deployment process just hangs indefinitely and only displays one public file on the website with an error message stating: "https://analogy-alley.hero ...

Building an easy-to-use jQuery task list

I'm currently working on a basic to-do list in Javascript, but I've encountered an issue. When I check the checkbox, the style of the adjacent text doesn't change as expected. Instead, it's the heading text that is affected by the chang ...

What is preventing me from reading the input value in AngularJS using jQuery?

Just starting out with angularjs and I need help with this code sample: <ng-input theme='fumi' id='txtEmail' label='Email Address' icon='icon icon--fumi mdi mdi-select-all' style="font-size:medium;width:40%;"&g ...

Using AJAX to send a POST request to a PHP backend server

Is it required to JSON.stringify the POST parameters/request object when making an AJAX POST call to a PHP backend? Can it be sent as a JS object without conversion? How does PHP handle them differently? Are there any recommended best practices for the re ...

How can one view all the static variables and methods associated with a class in Typescript or ES6?

Is it possible to retrieve all static variable names and static method names associated with a class, similar to how the Object.keys method returns a list of key names attached to an object? Typescript Example: class FindStatics { static num1:string = ...

Using React to pass a state value as a parameter in a method

Looking for a way to increase the reusability of my class. Dealing with a large form and don't want to create a unique method for each input. How can I pass the state value as a parameter to the method? I attempted the following approach: state = ...

Harness the power of React Material-UI with pure javascript styling

I am currently attempting to implement Material-UI in pure javascript without the use of babel, modules, jsx, or similar tools. <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8 ...

How can you incorporate a displacement map onto a mesh using the Three.js framework?

JSFiddle: http://jsfiddle.net/ma791nd8/1/ I'm encountering some challenges due to outdated tutorials and limited documentation, which is why I've decided to seek assistance here. After reviewing one of the examples provided, I created a jsfiddl ...

JavaScript: Choosing an element by class within the current row using jQuery

One of my tasks involves generating a table with values fetched from a database. The column totals are displayed at the end of the table. I am looking to provide users with the option to remove specific rows they do not wish to see, and have the total auto ...

Encountering a bizarre npm issue while attempting to execute npm install for brain.js

Encountering a puzzling error while attempting to install brain.js. Unsure of why Python is being mentioned during the installation process via npm, as there are no similar situations found on Google (and I'm not quite sure how to search for it). G:& ...

Error: Unable to use the map method on data in Reactjs because it is not

I'm currently working on a project with React.js and using Next.js as well. I'm attempting to fetch data from an API, but I keep encountering the following error: TypeError: data.map is not a function Below is the code snippet from the Slider.js ...

Updating the state using ui-router

The application consists of pages labeled as X, Y, and Z. The intended route is to navigate from page X to select details, then move onto page Y to select additional details, and finally land on page Z. I wish that upon clicking the window's back butt ...