Is there a more efficient method than repeatedly using _.groupBy?

After performing this action, I end up with an array that organizes the data by month and day of the date, but not by year. This grouping is done to calculate the maximum, minimum, and average values for each available data point.

The issue arises from the fact that the array contains 2-3 values for a specific day and month under the key value of the date. Each of these indices holds an array of length one, which references an object containing the necessary data point (level). The object includes three attributes: date, id (which is always null), and level as a float.

I am looking for a way to either directly store the object within those indices or allow _.each to access the level attribute.

Any suggestions?

var groupedData = _.groupBy(data, "date");

var groupedLevels = _.groupBy(groupedData, function (points, date) {
  var dateParsed = parseDate(date);
  var month = dateParsed.getMonth();
  var day = dateParsed.getDate();

  var monthDay = month + "-" + day; 
  return monthDay;
});

_.each(groupedLevels, function (points, date) {
  var levels = _.map(_.pluck(points, "level"), parseFloat);

  minimum.push([ date, R.min(levels) ]);
  maximum.push([ date, R.max(levels);

  var averageLevel = R.sum(levels) / levels.length;

  average.push([date, averageLevel]);
})

The original input data looks like this:

[ { date: "2009-01-01",
    id: null,
    level: "0.08",
  },
  // ...
]

Currently, groupedData appears as follows:

{ "2009-01-01":
  [ { date: "2009-01-01",
      id: null,
      level: "0.08"
    }
  ],
  // ...
}

An example structure of groupedLevels is shown below:

{ "0-1":
  [ [ { date: "2009-01-01".
        id: null,
        level: "0.08"
      }
    ],
    // ...
  ],
  // ...
}

My goal is to eliminate the arrays of length one and directly store the object instead.

Answer №1

In my opinion, you can resolve the current issue by making a small adjustment to this specific line:

var levels = _.map(_.pluck(points[0], "level"), parseFloat);

Instead of having multiple groupBy functions, you might be overcomplicating things. This single groupBy should do the trick without any unnecessary nested arrays:

var groupedLevels = _.groupBy(data, function(item) {
  var dateParsed = parseDate(item.date);
  var month = dateParsed.getMonth();
  var day = dateParsed.getDate();
  return month + '-' + day;
});

By implementing this change, your each function should function correctly.

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

Retrieving data from a backend express server using Client-side Javascript

I have created an Express Server set up in the following way: var mysql = require('mysql2'); var express = require('express'); var app = express(); var PORT = 3000; app.get('/getDataFromDatabase', function(req, res) { cons ...

Guide on transforming a PHP array encoded in JSON into a JavaScript array

After fetching a JSON encoded array via AJAX from a PHP file, I need to manipulate it as an array in JavaScript. How can I achieve this? Here is my AJAX call to the PHP File: $.ajax({ type:"POST", url:"ajaxfetch.php", success:function(re ...

Is it possible to include alligator tags(<% %>) within a JavaScript string?

I am attempting to redirect a page by pulling the url from the config file. However, when I try the following code: <script type="text/javascript"> <%string redirectUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["RedirectU ...

Acquire the worth of the <MenuItem> element from React's mui/material library

I am attempting to retrieve the value of the selected item listed below: Here is my attempt at logging this information: console.log("Event: ", event.currentTarget); Output: <li class="MuiButtonBase-root MuiMenuItem-root MuiMenuItem-gut ...

Can you please explain the significance of this error for me?

I'm attempting to showcase specific elements from an array in my code. <?php $data = array( 1000 => array( "id" => 1000, "number" => 2380, "name" => "CS2", "instructor" => "Chen", "rating" => null ), 1001 => a ...

Distinguishing between web development, frontend, and backend: Identifying ownership of an entity by a user

In my web application, I have a setup where each user can have multiple projects and each project can have multiple users. This relationship is managed through three tables in the database: user, project, and user2project which maps the n:m relation betwee ...

Is there a way to identify rows containing identical elements in a two-dimensional matrix?

I have a unique matrix with custom dimensions, and I am trying to identify a line with a specified length. I need to determine the coordinates of the first and last elements in this line. For instance: Assuming the line length is 3. Consider the foll ...

When combining stores, what sets Mobx.inject apart from Mobx.observer?

As I start integrating my store with mobx, a question arises in my mind. What sets apart the usage of observer(['store'],...) from inject('store')(observer(...))? Upon closer examination, it seems that inject is not reactive. So, what ...

What is the reason for index always being not equal to 0?

<script> var index = 0; $.getJSON("./data/data.json", function(json) { $.each(json, function(data) { var html = ""; if(index == 0) { console.log(index + " fir ...

Why is my Jquery not selector failing to target a specific child element?

$(document).on('click', '#ul li:not(.info)', function(){ alert(); }); This is what my HTML code looks like <ul id="ul"> <li></li> <li><a href="#" class="info"></li> </ul> I'm wonder ...

I'm having trouble with an error in my React project on VS Code. Can anyone provide guidance

Could you please explain the meaning of this error message: errno: 'ENOENT', code: 'ENOENT', syscall: 'spawn cmd', path: 'cmd', spawnargs: [ '/s', '/c', 'start', '""', ...

Ways to compare values in an array and then add the array in PHP

Below you'll find the code I've been working on. I am attempting to create a graph using values from the following array: In the dates array, I have all 30 days listed. I also have arrays named pending_date and approved_date. My goal is to match ...

Discovering techniques to access nested objects in JavaScript

My initial object state looks like this: answersCount: { Colors: { Green: 0, Brown: 0, Blue: 0, Red: 0 }, Letters: { A: 0, B: 0, C: 0, D: 0, }, Briggs: { EI: 0, SN: 0, T ...

XML does not operate like a conventional function

I've been struggling with this issue for hours. Does anyone know how to fix it? I keep getting an error message saying "xmlDoc is not a function". var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; loadXMLDoc(); function loadXMLDoc() { ...

The scroll-to-top button refuses to fade out

I am currently facing a challenge with my scroll to top button not functioning properly. It seems like there is an issue arising from another animation that I can't seem to pinpoint. Specifically, when the other animation is triggered at "scroll hits ...

Mastering the Art of Mocking DOM Methods with Jest

What is the best way to simulate this code snippet using Jest : useEffect(() => { document .getElementById('firstname') ?.querySelector('input-field') ?.setAttribute('type', &apos ...

The battle between ui-sref-active and $state.includes() is a topic of

I am attempting to highlight the clicked area by adding an active class using ui-sref-active. Unfortunately, it is not working with $state.includes(), even though I can see its value as true in the controller. Can someone assist me with this issue? See th ...

Transfer information from an array to a Vue function

Having some difficulties passing data to the function myChart within the mounted section. As a beginner in vuejs, I'm struggling with identifying the issue. I am trying to pass data in labels and datasets, which are called from my function. Can anyone ...

Evaluating the values of one array in comparison to those of another array

Exploring arrays and comparing their values. Here is an example of an array with values: arr1 = [1,5,6,7,3,8,12]; Now we have another array that we want to compare with: arr2 = [3,5,7]; We need to check if all the values in arr2 are present in arr1. f ...

What is the best location for storing your front-end javascript files?

As I work on my web application using Express, I've utilized the application skeleton provided by the express-generator. To bundle my client-side assets, I've integrated webpack into my project. Now, I'm faced with a dilemma on where to st ...