Calculate the minimum, maximum, and average values within an array containing nested elements

I want to calculate the min, max, and average values for nested data that already have these values precalculated. Essentially, I'm looking for the average of averages, min of min, and max of max.

I have a large dataset that includes the min, max, and average scores for each user:

[
    {
        "name": "Joe",
        "data": [
            [
                22323,
                180.269944190979,
                {
                    "min": 148608,
                    "max": 486656,
                    "avg": 123
                }
            ],
            [
                12312,
                180.269944190979,
                {
                    "min": 148608,
                    "max": 486656,
                    "avg": 2
                }
            ],
            [
                232,
                180.269944190979,
                {
                    "min": 148608,
                    "max": 486656,
                    "avg": 2323
                }
            ]
        ]
    },
    {
        "name": "Miranda",
        "data": [
            [
                1641466800000,
                180.269944190979,
                {
                    "min": 148608,
                    "max": 486656,
                    "avg": 123
                }
            ],
            [
                12312,
                180.269944190979,
                {
                    "min": 148608,
                    "max": 486656,
                    "avg": 2
                }
            ],
            [
                232,
                180.269944190979,
                {
                    "min": 148608,
                    "max": 486656,
                    "avg": 2323
                }
            ]
        ]
    },
    {
        "name": "Eli",
        "data": [
            [
                1641468540000,
                5630.96112537384,
                {
                    "min": 0,
                    "max": 384048,
                    "avg": 237031.22959263306
                }
            ],
            [
                1641468420000,
                5688.5411739349365,
                {
                    "min": 157216,
                    "max": 384048,
                    "avg": 248715.63971152372
                }
            ],
            [
                1641468300000,
                5832.6060581207275,
                {
                    "min": 0,
                    "max": 372560,
                    "avg": 226729.37108433736
                }
            ],
            [
                1641468360000,
                5836.711280345917,
                {
                    "min": 0,
                    "max": 384048,
                    "avg": 274216.2701236057
                }
            ]
        ]
    }
]

I'm struggling to calculate the average, min, and max values within each object. For example, I want the following result:

[
    {
        "name": "Joe",
        "details": {
            "min": 0,
            "max": 12332,
            "avg": 9594.43435
        }
    },
    {
        "name": "Miranda",
        "details": {
            "min": 0,
            "max": 65443,
            "avg": 1231233.2442
        }
    },
    {
        "name": "Eli",
        "details": {
            "min": 0,
            "max": 312321,
            "avg": 544545.3345
        }
    }
]

I've attempted to use the reduce function but I'm unable to retain the previous value.

I struggle with lodash:

data.reduce((acc, val: any) => {
              acc.min = acc.min + val[2].min;
              return acc;
            }, { min: 0, max: 0, avg: 0 })

Answer №1

To achieve the desired output, you will need to use a combination of map and reduce:

const input=[{name:"Joe",data:[[22323,180.269944190979,{min:148608,max:486656,avg:123}],[12312,180.269944190979,{min:148608,max:486656,avg:2}],[232,180.269944190979,{min:148608,max:486656,avg:2323}]]},{name:"Miranda",data:[[16414668e5,180.269944190979,{min:148608,max:486656,avg:123}],[12312,180.269944190979,{min:148608,max:486656,avg:2}],[232,180.269944190979,{min:148608,max:486656,avg:2323}]]},{name:"Eli",data:[[164146854e4,5630.96112537384,{min:0,max:384048,avg:237031.22959263306}],[164146842e4,5688.5411739349365,{min:157216,max:384048,avg:248715.63971152372}],[16414683e5,5832.6060581207275,{min:0,max:372560,avg:226729.37108433736}],[164146836e4,5836.711280345917,{min:0,max:384048,avg:274216.2701236057}]]}];

const result = input.map(item => {
    const details = item.data.reduce( (acc,i) => {
      const val = i[2];
      acc.min = Math.min(val.min, acc.min);
      acc.max = Math.max(val.max, acc.max);
      acc.sum += val.avg
      return acc;
    },{min:Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY, sum:0})
    
    return {
        name: item.name,
        details:{
          min: details.min,
          max: details.max,
          avg : details.sum/item.data.length
        }
    }
});

console.log(result);

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

Having trouble understanding why ng-resource refuses to return an array

I've recently encountered an issue while using AngularJS and NGResource. For some reason, every time I try to use the query function, I receive an empty array in return. Within my controller, the code looks like this: Task = $resource('/tasks&a ...

Uploading a screenshot to a server using Ionic 4

I have encountered an issue while trying to take a screenshot and upload it to a server using the spring-boot. I utilized a native library for taking the screenshot and an Angular service to obtain the image URI. I converted the image URI to a blob and sen ...

Exploring the differences between scoping with let and without any scoping in

Within my code, there is a forEach loop containing a nested for loop. It's interesting that, even though I have a statement word = foo outside of the for loop but still inside the forEach loop, I can actually log the value of word after the entire for ...

Struggling to process the JSON file with Java's parsing?

I'm encountering an error while trying to parse the JSON file below. Any help would be greatly appreciated! {"Name":"Abc", "Author":"fgd", "Company List":{"Company":"C1","Companyone":"Compa2"}} Check out my code snippet:- JSONParser parser = new JS ...

Creating "search result pages" with HTML, PHP, Javascript, and MySQL

Consider the scenario where you have a table with two columns: id and name, containing thousands of rows. You have a search engine that allows searching by free text, using the query: SELECT * FROM `table` WHERE `name` LIKE '%$search%' The res ...

Component not refreshing when state changes occur

I have a unique react application that resembles the one showcased in this codesandbox link https://codesandbox.io/s/eatery-v1691 By clicking on the Menu located at the bottom center of the page, it triggers the display of the MenuFilter component. The M ...

When using Typescript, I am encountering an issue where declared modules in my declaration file, specifically those with the file

One of the declarations in my ./src/types.d.ts file includes various modules: /// <reference types="@emotion/react/types/css-prop" /> import '@emotion/react'; import { PureComponent, SVGProps } from 'react'; declare mod ...

Error encountered while attempting to render a form within a partial in Rails 5: "simple_fields_for" method is not defined for the SimpleForm::FormBuilder instance

This is a continuation from this thread: Passing a form as a local to a ajax rendered partial in Rails 5 I've searched extensively but haven't been able to find a working solution. Relevant Controller (profits_controller.rb): def new_tabs ...

In PHP, what is the best way to close the HTML tags found in this array?

I am struggling with an array that contains HTML tags and I need to create a formatted output using a PHP function. However, I am having trouble closing the tags correctly and would appreciate some assistance. The existing array is structured line by line ...

Guide to retrieving and editing images from Appwrite using Vue

Currently, I am utilizing a View frontend to retrieve a PDF file from Appwrite Storage. My goal is to acquire the PDF, insert additional text onto it, and then save it to the user's local device. Below is the code I have so far - although I can recei ...

Retrieving the Selector Value during a Change Event

Is there a way to retrieve the selector value in a change event? I attempted this approach: $("#frek_menonton_tv :input").change(function(){ $(this).selector; }); However, it only returns an empty string. Desired outcome: frek_menonton ...

Create a separate child process in Node.js

Is it possible to create a separate process from the current script? I want to execute another script while the original one is still running. This new script should be completely independent of the calling script. ...

Effortlessly switching classes in JavaScript for seamless transitions

I'm currently working on an animation project where I want the title to be visible on the page initially, and then slowly fade away as you scroll down, with a subtitle fading in right after. While I've managed to get the title part working, I&apo ...

Revising Your Task Checklist with React

I encountered an issue while attempting to update the value retrieved from Addlist. Unfortunately, my solution isn't working as expected. Additionally, clicking on the '+' button without entering any text results in an empty list being creat ...

The CSS Bootstrap 4 class 'input-group-append' is not functioning properly. Just recently, the styles were displaying correctly

My web application using AngularJS 1.7.8, jQuery 3.3.1, Bootstrap 4.3.1, and various other CSS and JS libraries worked seamlessly last week. However, today I noticed an issue with the button visualization. To Replicate: Visit openskymap.org to see my d ...

Vue components: Using `object[key]` as a prop does not trigger reactivity

I'm attempting to bind a value from an Object into the prop of a Component, but unfortunately it is not reacting as expected. Despite using $this.set, the reactivity issue persists. Below is my template: <div class="grid"> <emoji-card v-fo ...

Unable to attach an onClick event handler to <TableRowColumn> element using Material-UI in React

In the past, I had a feature that allowed me to change the color of the text from red to green by clicking on a table cell. After introducing Material-UI in my React app and replacing the <td> tags with <TableRowColumn> tags, I noticed that th ...

Java program that reads data from a file, saves the string information into an array, and then modifies and writes this string data

I've been grappling with this question for hours, so any help would be greatly appreciated. My task is to read a file via command line argument that contains information about several students - their names, majors, IDs, and graduation dates. I then n ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

JavaScript obtain scroll position of a child element

I have a setup that looks something like the following: <div> <div id="scrollID" style="height:100px;"> content here </div> </div> <script> document.getElementById("myDIV").addEventListener("touchstart", m ...