Discover the highest value within an array of objects, along with any numerical object attributes that have a value greater than zero

Considering an array of objects structured as follows:

[{
    "202201": {
        "WO": 900,
        "WS": 0,
        "SY": 0.915,
        "LY": 0.98,
        "CT": 75
    },
    "202202": {
        "WO": 300,
        "WS": 0,
        "SY": 0.915,
        "LY": 0.98,
        "CT": 73
    },
    "202203": {
        "WO": 350,
        "WS": 0,
        "SY": 0.915,
        "LY": 0.98,
        "CT": 68
    },
    "202204": {
        "WO": 400,
        "WS": 0,
        "SY": 0.915,
        "LY": 0.98,
        "CT": 77
    },
    "202205": {
        "WO": 300,
        "WS": 0,
        "SY": 0.915,
        "LY": 0.98,
        "CT": 67
    },
    "Product": "A",
    "Facility": "a-Facility"
},
{
    "202201": {
        "WO": 6665,
        "WS": 0,
        "SY": 0.903,
        "LY": 0.993,
        "CT": 73
    },
    "202202": {
        "WO": 5907,
        "WS": 0,
        "SY": 0.903,
        "LY": 0.993,
        "CT": 71
    },
    "202203": {
        "WO": 5893,
        "WS": 0,
        "SY": 0.903,
        "LY": 0.993,
        "CT": 74
    },
    "202204": {
        "WO": 5486,
        "WS": 0,
        "SY": 0.903,
        "LY": 0.993,
        "CT": 67
    },
    "202205": {
        "WO": 5448,
        "WS": 0,
        "SY": 0.903,
        "LY": 0.993,
        "CT": 69
    },
    "Product": "B",
    "Facility": "b-Facility"
}]

The objective is to determine the highest "CT" (cycle time) for all products at a manufacturing line encompassing all facilities. In this instance, the maximum CT value is 77.

A comparable and contemporary approach can be found here:

Math.max(...array.map(o => o.y))
referenced in this query regarding max value extraction from an object array, although it does not delve into numeric properties of each object within an array.

I believe there's a method to map not just the array of objects, but also the object attributes with a "CT" property (replacing "undefined" with 0) to identify the aforementioned maximum value of 77. Further exploration will ensue while awaiting assistance.

This is a typescript application, however, a javascript solution will suffice.

PROGRESS:

An advanced alternative to double for loops is desired, hence if you can present superior options, it would be greatly appreciated:

numbers = [];
data.forEach(d => {
    numbers = numbers.concat(Object.keys(d).map(p => d[p].CT ? d[p].CT : 0));
})

maxCycle = Math.max(...numbers);
data.forEach(d => {
    for (const w in d) {
        maxCycle = maxCycle < d[w]['CT'] ? d[w]['CT'] : maxCycle;
    }
});

Answer №1

To find the maximum value from an array, you can utilize the Array.flatMap method.

Here is a concise one-liner that accomplishes this task:

Math.max(...arr.flatMap(i => Object.values(i)).flatMap(obj => obj.CT || -Infinity))

In this code snippet, we use two consecutive calls to flatMap. The first one extracts the values of objects in the array, and the second accesses the CT property within each object.

By using -Infinity as the default value instead of 0, even cases with negative values will be considered correctly.

const arr = [{
    "202201": {
      "WO": 900,
      "WS": 0,
      "SY": 0.915,
      "LY": 0.98,
      "CT": 75
    },
    "202202": {
      "WO": 300,
      "WS": 0,
      "SY": 0.915,
      "LY": 0.98,
      "CT": 73
    },
    "202203": {
      "WO": 350,
      "WS": 0,
      "SY": 0.915,
      "LY": 0.98,
      "CT": 68
    },
    "202204": {
      "WO": 400,
      "WS": 0,
      "SY": 0.915,
      "LY": 0.98,
      "CT": 77
    },
    "202205": {
      "WO": 300,
      "WS": 0,
      "SY": 0.915,
      "LY": 0.98,
      "CT": 67
    },
    "Product": "A",
    "Facility": "a-Facility"
  },
  {
    "202201": {
      "WO": 6665,
      "WS": 0,
      "SY": 0.903,
      "LY": 0.993,
      "CT": 73
    },
    "202202": {
      "WO": 5907,
      "WS": 0,
      "SY": 0.903,
      "LY": 0.993,
      "CT": 71
    },
    "202203": {
      "WO": 5893,
      "WS": 0,
      "SY": 0.903,
      "LY": 0.993,
      "CT": 74
    },
    "202204": {
      "WO": 5486,
      "WS": 0,
      "SY": 0.903,
      "LY": 0.993,
      "CT": 67
    },
    "202205": {
      "WO": 5448,
      "WS": 0,
      "SY": 0.903,
      "LY": 0.993,
      "CT": 69
    },
    "Product": "B",
    "Facility": "b-Facility"
  }
]

console.log(Math.max(...arr.flatMap(i => Object.values(i)).flatMap(obj => obj.CT || -Infinity)))

Answer №2

const largestValue = data.reduce((accumulator, current) => {
    for(value of Object.values(current)) {
        if(typeof(value) === 'object') {
            for(key in value) if(key === 'CT' && value[key] > accumulator) accumulator = value[key];
        }
    }
    return accumulator;    
}, 0);

This is a more concise version:

const largestValue = data.reduce((acc, item) => {
    for(value of Object.values(item)) if(typeof(value) === 'object') for(key in value) if(key === 'CT' && value[key] > acc) acc = value[key];
    return acc;    
}, 0);

[Improved] Even More Optimized Solution

const largestValue = data.reduce((acc, current) => {
    for(value of Object.values(current)) if(value['CT'] > acc) acc = value['CT'];
    return acc;    
}, 0);

I hope this revised explanation is helpful!

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 automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

What is the best way to implement a slide-down animation on a stateless component in React JS using either ReactCSStransitionGroup or ReactTransition

I am looking to create an animation for a stateless component that starts off with display:none, and then becomes visible when the parent component's state changes. I want it to slide down like a dropdown menu effect. I am new to animations and have b ...

PHP code for formatting a JsonArray

I am currently unable to format it the way I would like. Initially, it appears as follows: {"success":true,"user":"tom","gender":"male","age":"2"} {"success":true,"user":"anna","gender":"female","age":"3"} However, the desired format is shown below: ...

Refining the nodes and connections within a directed graph by implementing a filter triggered by clicking a button

I have successfully implemented a force-directed graph. My next step is to incorporate buttons in the main HTML data to enable further filtering. Unfortunately, I haven't been able to make it work yet. I would greatly appreciate any suggestions or gui ...

Removing the arrow icon preceding an image in a new line when dealing with dynamic data

My Angular project renders dynamic content that includes the following HTML structure: <div class="complted" *ngFor="let step of letStep1to7; let i = index; let first = first"> <table> <td class="steps" ...

What is the best way to have an icon appear when a child component div is clicked, without it displaying on other similar divs?

Within my child component div, I have configured it to display information from an object located in the parent component. Initially, when the web app loads, it correctly shows three divs with names and messages retrieved from the created object. However, ...

Attempting to integrate WebdriverIO into an Angular Electron application

Context: Currently, I am in the process of implementing the fundamental WebdriverIO example within an Angular Electron App. My application is built on the foundation of the Angular Electron Boilerplate. To set up, I have installed webdriverio and @types/we ...

Unable to retrieve the image

When trying to fetch an image, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) TopBar.jsx import { useContext } from "react"; import { Link } from "react-router-dom"; ...

Turn off Satellizer Popup Window Title Bar

Currently, I am implementing the satellizer plugin for Facebook authentication. However, I have encountered an issue with the default popup login window of Facebook, which includes a title bar and menu options. I would like to transform this popup into a m ...

Issue: Expressjs is throwing a TypeError due to an attempt to read the 'id' property of undefined

I am currently working on a registration function in expressjs, but I keep encountering the following error message: TypeError: Cannot read properties of undefined (reading 'id') This is my user model: Users.ts interface UserAttributes { id: ...

Retrieving attributes from a reactive object in TypeScript

I have a question regarding accessing values in Typescript. Whenever I load my website, I make a call to a service that fetches user data. private currentUserSource = new ReplaySubject<IUser>(1); currentUser$ = this.currentUserSource.asObservable ...

Having trouble concealing the logout button even after signing out with ng-show in angularjs

The code for displaying the logout button is as follows: <li class="dropdown" data-ng-if="userName"> <a href class="dropdown-toggle clear" data-toggle="dropdown" data-ng-show="userName"> </a> <!-- dropdown --> <u ...

Is there a way to stream an mp3 file in a Node.js REPL on Replit?

I have an MP3 file that I want to play when a button is clicked. However, I suspect that I am not correctly serving the file to the server. The following code snippet is from my project on Replit.com: const app = require('express')(); const http ...

Troubleshooting problem with the oninput function of a custom JavaScript element

Assume I have a unique requirement to trigger a function within a custom element. The goal is to update text in the element only when a slider is moved within that specific element. Here's an example implementation in the main.js file: class Oninput ...

successful callback after passport registration

router.post('/register', function(req, res, next){ var name = req.body.name; var email = req.body.email; var username = req.body.username; var password = req.body.password; var password2 ...

What is the quickest method for importing React.js Material Icons in a single line of code?

While working on my initial react.js project as a beginner, I encountered the frustration of having to import Material UI icons individually. This process made my code unnecessarily long and required me to repeatedly visit the browser to copy the icon li ...

Instructions on utilizing Tesseract.recognize in Node.js

I am working on developing an OCR program but encountered some issues while declaring the 'Tesseract.recognize' method. Here is the code snippet: const express = require('express'); const fs= require('fs'); const multer = r ...

Determining the data type of an object key in Typescript

Is there a way to limit the indexed access type to only return the type of the key specified? interface User { id: string, name: string, age: number, token: string | null, } interface Updates<Schema> { set: Partial<Record< ...

What could be the reason for the component failing to update even after modifying the object's properties?

I have come across some related threads on Stack Overflow, but they only briefly mention using the spread operator. But why should we use it? In the code below, I am trying to update the firstName property of the user object, which is a state, when clicki ...

Select elements using jQuery in events while excluding others

I need to prevent form submission when the user presses Enter, except for three specific inputs. To prevent form submission on Enter key press, I can use this code: $(document).keydown(function(event){ if(event.keyCode == 13) { event.preventDefault(); re ...