Transforming an array of objects into a new array containing the average numbers of each object

I'm working with an array that needs manipulation in order to use it as a data source for D3.js. The dataset looks like this:

var data =  [
 {day: 1, month: 1,  length: 100,  year: 2010},
 {day: 2, month: 1,  length: 125,  year: 2010},
 {day: 3, month: 1,  length: 150,  year: 2010},
 {day: 4, month: 1,  length: 175,  year: 2010},
 {day: 1, month: 2,  length: 225,  year: 2010},
 {day: 2, month: 2,  length: 250,  year: 2010},
 {day: 3, month: 2,  length: 325,  year: 2010},

 {day: 1, month: 1,  length: 225,  year: 2011},
 {day: 1, month: 1,  length: 150,  year: 2011},
 {day: 1, month: 1,  length: 190,  year: 2011},
 {day: 1, month: 2,  length: 210,  year: 2011},
 {day: 2, month: 2,  length: 110,  year: 2011},
 {day: 3, month: 2,  length: 160,  year: 2011},
 {day: 4, month: 2,  length: 190,  year: 2011},
]

My goal is to create a new array with average lengths per month. For example:

var newData = [ [137.5, 266.7], [183.33, 167.5] ]

In this array, newData[0][1] represents the average length of month 1 in year 2010.

I have managed to calculate the sum of lengths but struggle with getting the averages. Here's the code I currently have:

data.forEach(function (el) {
   for (var j = 0; j <= 3; j++) {
     if (el.year === 2010 + j) {
       for (var i = 1; i <= 2; i++) {
                if (el.month === i) {
                    var oldLength = dataNew[j][i - 1] || 0;
                    var newLength = el.length + oldLength;
                    dataNew[j][i - 1] = newLength;
                }
        }
     }
   }
});

I need help adjusting this function to store averages instead of sums in the newData array.

Answer №1

Enhance your code readability and streamline your work with the assistance of d3.js itself. By utilizing d3.nest(), you can organize your data efficiently.

var data =  [
 {day: 1, month: 1,  length: 100,  year: 2010},
 {day: 2, month: 1,  length: 125,  year: 2010},
 {day: 3, month: 1,  length: 150,  year: 2010},
 {day: 4, month: 1,  length: 175,  year: 2010},
 {day: 1, month: 2,  length: 225,  year: 2010},
 {day: 2, month: 2,  length: 250,  year: 2010},
 {day: 3, month: 2,  length: 325,  year: 2010},

 {day: 1, month: 1,  length: 225,  year: 2011},
 {day: 1, month: 1,  length: 150,  year: 2011},
 {day: 1, month: 1,  length: 190,  year: 2011},
 {day: 1, month: 2,  length: 210,  year: 2011},
 {day: 2, month: 2,  length: 110,  year: 2011},
 {day: 3, month: 2,  length: 160,  year: 2011},
 {day: 4, month: 2,  length: 190,  year: 2011},
]

var nest = d3.nest()
    .key(function(d){return d.year})
    .key(function(d){return d.month})
    .rollup(function(d){
        return d3.mean(d, function(g){return g.length});
    })
    .entries(data)

console.log(nest[0].values[0]) // 137.5

Check out this interactive example on JSFiddle.

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

Is there a way to use Javascript to verify if a window is fully open?

Is there a way to detect the complete opening of a window using JavaScript? // code1 is not functioning $(window).resize(function() { ... }); // code2 is not working window.onresize = function(event) { ... } I am ...

PHP - Managing arrays in programming

Given the array provided below, what is the best way to determine if vid equals 2 and then output or retrieve tid? Array ( [29] => stdClass Object ( [tid] => 29 [vid] => 2 [name] => notebook ...

Is there a way to execute two files concurrently in JavaScript using node.js?

I'm a beginner in the world of Javascript and Node.js, and I've encountered some issues while trying to test code I recently wrote. Specifically, I am attempting to test the code within a file named "compareCrowe.js" using another file named "tes ...

How to dynamically set Bootstrap navbar item as active based on current filename?

Currently, as I construct my website using the bootstrap framework, I am facing a minor challenge. I want to activate a menu item based on the filename by utilizing an if statement. For instance, when the filename is "about," the "about" tab should be act ...

What is the best way to determine the MIME type of a file URL found on the internet?

Is there a method to determine whether the file I am fetching from a URL is an image or a video? What is the process to distinguish between an image and a video type, and display them appropriately on my website? I'm working with next.js and aiming ...

The process of implementing image validation in PHP, such as checking for size and weight restrictions,

Can someone assist me with inserting an image in PHP, along with validation for size and weight? If the size or weight is incorrect, I need to display an error message. Please provide guidance... PHP script needed... if (isset($_POST['submit']) ...

Error: $(...).DataTable function is not recognized - DataTables requires $.noConflict(true) to function properly

Recently I stumbled upon DataTables and decided to experiment with it. My goal for the page is to search and display posts based on user-defined parameters, updating the table content with JSON without having to refresh the entire page. However, I'm e ...

Using JavaScript to transform a string into a multidimensional array

I am currently working with sockets (server and client) and I have been attempting to send a matrix. My goal is to send a string array and then convert it into a variable called "ARRAY". For instance, if I want to send an array structured like this: edit ...

Why does my counter keep incrementing by more than one every time?

As I work on creating a test in jQuery, I've encountered an issue with my counter variable count. It seems to increase by more than one when the correct answer is used. function nextQuestion(){ $('#submit').show(); $('#next&apo ...

Creating a webpage that seamlessly scrolls and dynamically loads elements

Currently, I am working on a dynamic website that loads new elements as you scroll down the page. Here is an example of the HTML code: <div>some elements here</div> <div id="page2"></div> And this is the JavaScript code: var dis ...

What is the best method for presenting nested JSON data in React using a key-value pair format?

This component serves as the product description section with tabs for both description and details. Selecting the description tab displays the product specifications in a tabular format. We are utilizing the Axios library to fetch JSON data from an API. I ...

"Is it possible for a JSON array to have a length of zero even

After receiving a JSON response from the server and converting it into a Javascript object, the structure looks like this: var response = { key1:[], key2:[], key3:[], key4:[], key5:[] } Once the request is complete, the response objec ...

Imported function encounters a non-function error

I'm encountering a puzzling reference/binding error that I can't seem to resolve: import React from 'react'; var { View, StyleSheet, Alert, AsyncStorage } = require('react-native'); import {Button} from 'react-native-el ...

What could be causing my Vuetify v-select in Vue 3 to send [object Object] instead of the chosen value?

I'm currently tackling a Vue 3 project with Vuetify, and I've encountered an issue involving a v-select component. The selected value is appearing as [object Object] instead of its actual value. Here's a simplified snippet of my code: Pare ...

Adjust the width of an HTML element as soon as a neighboring element is added

My objective is to achieve automatic resizing of an HTML element. This is the script I am using: <html> <head> <style> .main{ background-color: blue; width: 500px; ...

Add the "i" item together with the "j" component and the "k" element within a Python program

I am currently working with 3 arrays that represent coordinates and data of a sparse matrix: cx=[3, 4, 3, 0, 1, 2, 1, 2] rx=[0, 0, 1, 2, 2, 2, 3, 4] data=[0.73646372, 0.42238729, 0.20987735, 0.33721646, 0.66935198, 0.13533819, 0.64143482, 0.004114] My goa ...

How can I use interpolation in a foreach loop in C#?

Below is the code snippet from my program: string[] strarray = new string[] {bird, lion, ape}; Array.Reverse(strarray); strarray.Reverse(); foreach(var value in strarray) { Console.Write(value.ToString( ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

What is the best way to expand this array and display it to the variable that called for

I need to transform a string that is structured like this: $string = "12,32,23,32-23X.12,32,23,32-20X"; Is there a way to convert this string into an array like the following: Array ( [0] => Array ( [0] => Array ( ...

How to easily toggle multiple elements using jQuery

I'm having trouble getting this block of code to function properly: $("a.expand_all").on("click",function(){ $(this).text('Hide'); $('.answer').each(function () { $(this).slideDown(150, function () { $( ...