Underscore performs calculations and outputs a fresh object as a result

Here is an example of a time series:

[
    {
        "_id": {
            "action": "click",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 5
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 13
    },
    {
        "_id": {
            "action": "hit",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 25
    },
    {
        "_id": {
            "action": "click",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 7
    }
]

In order to calculate the percentage between clicks and hits for each date, you can return a new object formatted like this:

[
    {
        "_id": {
            "action": "ctr",
            "date": "2015-02-02T00:00:00+01:00"
        },
        "total": 38.46
    },
    {
        "_id": {
            "action": "ctr",
            "date": "2015-02-03T00:00:00+01:00"
        },
        "total": 28
    }
]

If you need any guidance on how to achieve this calculation, feel free to ask!

Answer №1

_.groupBy(arr, function(element){ return element._id.date; });

This is a simple way to group elements in an array, and then perform calculations as needed. For example:

http://jsfiddle.net/j9Htk/114/

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

Encountering a ReferenceError stating that the window object is not defined while building a React Leaflet application

In my upcoming nextjs project, I've incorporated react-leaflet. It behaves flawlessly in dev mode. However, upon attempting to build the project, it throws a ReferenceError: window is not defined. Despite setting ssr to false in dynamic, the error per ...

What could be the source of the "Uncaught Error: write after end" error occurring in my test cases?

Below is the code I am working with: var Promise = require('bluebird'); Promise.longStackTraces(); var path = require('path'); var fs = Promise.promisifyAll(require('fs-extra')); var clone = require('nodegit').Clone ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...

What is the best way to trigger the Javascript blur event following a click event that results in the element losing focus

Encountering this issue multiple times has left me dissatisfied with the solutions I've implemented in the past. The challenge lies in dealing with an input box that triggers a validation process on blur, while also having a button that populates the ...

What is the most effective method for filtering a table using both column-specific and global filters?

Looking for the most efficient way to filter a large chunk of JSON data client-side using a table? Each header has an input filter where users can enter a string to filter that specific property. There is also a global filter for free text search. If you ...

Refreshing PHP code automatically within a JavaScript function

Currently working on a Pi project to create a monitoring web page for tracking power readings from a meter. Adding some aesthetic gauges using canvas-gauges (). A python script running in the background fetches data from the meter and saves it to a file e ...

A guide on passing an array parameter using JavaScript

I need to transfer an array of ids from one page to another. I have created the $ids variable in PHP, and I am using it with jQuery like this: var ids = <?php echo json_encode($ids); ?>; jQuery(ids).each(function() { filters.push('ids[]=&a ...

JSONP request resulted in a syntax error

I'm having trouble retrieving data from a JSONP source, as it keeps throwing a Syntax error when the function is called. I am quite new to this subject and find it hard to understand why this error occurs. It seems like my understanding of JSONP reque ...

AngularJS - Using filters to extract specific options from multiple <select> components

There are N "select" components generated based on JSON data, with the "options" populated by an external API. I am trying to implement a custom filter that ensures when an option is selected in one "select" component, it should not appear in the other com ...

Set the timezone of a Javascript Date to be zero

Is there a way to create a Javascript date without any specific timezone? When I try to do so in Javascript, it automatically sets it to GMT Pacific standard time. let newDate = new Date(new Date().getFullYear(), 0, 2, 0, 0, 0, 0) }, newDate: Sat Feb 01 2 ...

What is the proper way to implement SSE/EventSource in your project?

After watching tutorials online, it seems common practice for authors to use SSE/EventSource in setting up a connection where the server-side PHP script echoes data and then uses ob_flush() and flush() to send the information back to the client's brow ...

The behavior of the Ionic checkbox in version 5 seems to be quite delayed

I am facing an issue with binding the checked attribute value on an ion-checkbox, as the behavior seems to be delayed. In my .ts file, I have an array variable named user_id. In my checkbox list, I am trying to populate this array based on which checkboxe ...

Fetching Information From Database Using PHP

I am encountering an issue while attempting to transfer data from my HTML table to my modal (without using bootstrap). In the image below, you can see that I have successfully displayed data from MySQL database in the table. The problem arises when I clic ...

Determine the maximum array size in Javascript

Having trouble setting a limit in my custom lightbox for a gallery <script> var imagenumber = 0; function btnleft(){ load = imagenumber-=1; document.getElementById('lightboxcontent').innerHTML=imagelist[load]; ...

You should only call them after the method that returns a promise has completed

submitTCtoDB() { console.log("The selected file list contains: " + this.selectedFileList) this.readFile().then(() => { alert("ReadFile has finished, now submitting TC"); this.submitTC() }); } readFile() { return new Promise((resolve, r ...

Create a sleek transition for your Bootstrap 4 fixed Navbar by having it smoothly slide down and change to a

Throughout my experience with HTML/CSS, I have predominantly relied on themes that included this feature by default. However, as I now venture into building from scratch, I find myself struggling to recreate it. You'll notice that I have a stylish fi ...

Discover the power of lodash's .groupBy method as you learn how to efficiently group objects within another

Utilizing lodash's _.groupBy function, I have generated the following data: { "Generic Drugs":[ { itemDes: "Dulcolax", itemGeneric: "Bisacodyl", pr ...

The pre-set value in the search bar of the Google specialized search

Is it possible to pre-fill the search field with text when the Google Custom Search page is loaded using the standard copy and paste code (free with ads)? If yes, how can this be achieved? Below is the code snippet: <div id="cse" style="width: 100%;" ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...

What is this error: "Unknown authentication strategy 'loca'"?

Whenever I try to utilize passport.js, it keeps throwing the following error: Unknown authentication strategy "local"! config/configuration.js var passport = require('passport') , LocalStrategy = require('passport-local').Strategy; ...