javascript utilizing underscorejs to categorize and aggregate information

Here is the data I have:

var dates = [
    {date: "2000-01-01", total: 120}, 
    {date: "2000-10-10", total: 100}, 
    {date: "2010-02-08", total: 100},
    {date: "2010-02-09", total: 300}
];

My goal is to group and sum the totals by year like this.

var grouped = [
    {date: "2000", total: 220}, 
    {date: "2010", total: 100}
];

I tried using underscorejs but couldn't find a suitable function.

var byYear = _.map(dates, function(item){ 
    var year = new Date(Date.parse(item.date)).getFullYear();

    return {date: year, total: item.total}; 
});

You can see the working code here.

Answer №1

Utilizing the reduce method. I noticed that this question had already been answered right before I could submit my response. Despite that, I had invested time in coding it so I will share it here anyway. It's worth noting that this solution involves chaining.

var byYear = _.chain(dates)
            .map(function(item){ 
                var year = new Date(Date.parse(item.date)).getFullYear();
                return {date: year, total: item.total}; 
            })
            .groupBy('date')
            .map(function (value,key) { 
                            var reduceVal = _.reduce(value, function (acc, val)
                                                            { 
                                                                return acc + val.total;
                                                            },0 ); 
                            return {'year':key,'total' :reduceVal};
                })
            .value();


alert(JSON.stringify(byYear));

Answer №2

It appears that you are in need of the reduce function:

var dates = [
    {date: "2000-01-01", total: 120}, 
    {date: "2000-10-10", total: 100}, 
    {date: "2010-02-08", total: 100}
];

var byYear = _.map(dates, function(item){ 
    var year = new Date(Date.parse(item.date)).getFullYear();        
    return {date: year, total: item.total}; 
});

var grouped = _.reduce(byYear, function(memo, item) {
    memo[item.date] = (memo[item.date] || 0) + item.total;
    return memo;
}, {});

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

Generating unique spreadsheet identifiers in an HTML file

When it comes to displaying a chart using Google Sheets, I encounter an issue where the data is sourced from the same spreadsheet: function updateChart() { var ui = HtmlService.createHtmlOutputFromFile('ChartLine').setWidth(1350).setHeight(550) ...

Unable to activate function when closing Vuetify v-alert

Is there a way to trigger a function when the Vuetify v-alert is closed? I have explored the documentation but haven't found any information on this specific functionality. In the codepen example, the dismissible attribute allows for closing the alert ...

There seems to be an issue with the accurate calculation of the screen width while utilizing the scrollbar-gutter

Please take note: The scrollbar-gutter: stable; property is not compatible with Safari. Additionally, the issue seems to be specific to Chrome and works fine in Firefox. I have observed some unusual behavior when attempting to position elements fixed to t ...

Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$f ...

Error: ReactJs unable to find location

I'm attempting to update the status of the current page when it loads... const navigation = \[ { name: "Dashboard", href: "/dashboard", current: false }, { name: "Team", href: "/dashboard/team", current: fa ...

Unlocking the Potential of NextJS with Dynamic Page Export - Say Goodbye to Static HTML!

I am attempting to export my NextJs project based on the official documentation provided. However, it seems that I can only export it into static HTML. Is there a way to export it into dynamic pages where user-submitted data is updated in real time, simil ...

Arranging objects in an array using jQuery for optimal organization

How can I rearrange the items based on their 'name' property? staticdata.items = [ {id: '0', 'name': 'ABC'}, {id: '0', 'name': 'XYZ'}, {id: '0', 'name': ' ...

Javascript: regular expression to validate alphanumeric and special characters

Looking to create a regular expression for a string (company/organization name) with the following conditions: No leading or trailing spaces No double spaces in between Shouldn't allow only a single character (alphanumeric or whitelisted) Can start ...

What is the best way to hide a custom contextmenu in AngularJs?

I created a custom contextmenu directive using AngularJs. However, I am facing an issue where the menu is supposed to close when I click anywhere on the page except for the custom menu itself. Although I have added a click function to the document to achie ...

Display data in Highchart legend only if it has values

In a unique scenario, I am required to compare various items and display the results in a chart. The user inputs two, three, or four article IDs and receives the corresponding data displayed in a chart. The issue arises when the user enters only two or th ...

Tips for maintaining interactivity after a page refresh

$(document).ready(function () { $("#2").click(function () { $("#content").load("{% url 'about' %}"); }); $("#3").click(function () { $("#content").load("{% url ...

Issues arise in Ionic 3 when attempting to use scripts or external custom jQuery plugins within inner pages

When I utilize a script tag in my index.HTML file, it functions properly on the initial or root pages of Ionic 3. However, upon navigating to other pages using NavController, the script ceases to work on these inner pages. How can I implement a custom jQ ...

Javascript - accessing a local file (located in the same directory as the HTML file, not an uploaded file)

I have been attempting to find a solution, but have had no success. Is there a way to read a file using JavaScript or HTML? I have a text file named "sample.txt" with some information in it. This file is located in the same folder as the HTML file that con ...

Is it really necessary to import React from 'react' in the index.js file when importing react is no longer required?

Currently diving into the world of React.js. I recently found out that after version 17, importing React is no longer necessary. My current React version is v18.2.0. Here's the code snippet in question: // import React from 'react'; import ...

Error in jQuery: Null property causing TypeError when reading 'text'

Issue: I have a modal form that is loaded via an ajax call. Inside the modal, there is a span element containing an email address. I am trying to capture the value of this span element using JavaScript. Currently, I have a button click event that triggers ...

Expanding Headers with JavaScript

Looking to add a Stretchy Header Functionality similar to the one shown in this GIF: Currently, on iPhones WebView, my approach involves calling a Scope Function On Scroll (especially focusing on Rubberband Scrolling) and adjusting the Image Height with C ...

Reverse the text alteration when the user leaves the field without confirming

Upon exiting a text box, I aim to display a confirmation dialogue inquiring whether the user is certain about making a change. If they select no, I would prefer for the text box to revert back to its original state. Is there an uncomplicated method to ach ...

How can I set a condition to open a specific page in ReactJs?

Currently, I am in the process of developing a website and have successfully implemented a profile page. This profile page consists of three buttons - Settings, Favourites, and Posts. To enhance user experience, I decided to structure it as a multi-step fo ...

Is there a way to create a header that fades out or disappears when scrolling down and reappears when scrolling up?

After spending some time researching and following tutorials, I have not made much progress with my goal. The task at hand is to hide the top header of my website when the user scrolls down and then make it reappear when they scroll back up to the top of t ...

"Enhance your website with Express.js and eliminate the need for full

As I continue to work on my website, I am faced with a challenge. While the page is not overly large, I want to ensure that when navigating to different tabs in the navbar, the entire site does not have to reload each time. Currently, I am using express.js ...