Retrieve the maximum numerical value from an object

My goal is to obtain the highest value from the scores object.

I have a global object called "implementations":

[
  {
    "id": 5,
    "project": 'name project',
    "scores": [
      {
        "id": 7,
        "user_id": 30,
        "implementation_id": 5,
        "score": "12.00",
        "comment": "C'est de la merde, ça vient d’Anthony."
      },
      {
        "id": 10,
        "user_id": 31,
        "implementation_id": 5,
        "score": "15.00",
        "comment": "Super"
      }
    ]
  },
  {
    "id": 6,
    "project": 'name project',
    "scores": [
      {
        "id": 8,
        "user_id": 30,
        "implementation_id": 6,
        "score": "20.00",
        "comment": "Super!"
      },
      {
        "id": 11,
        "user_id": 31,
        "implementation_id": 6,
        "score": "12.00",
        "comment": "Super"
      },
      {
        "id": 15,
        "user_id": 36,
        "implementation_id": 6,
        "score": "10.00",
        "comment": "Super"
      }
    ]
  }
]

As illustrated in the above object, there are 2 scores in object 1, and 3 scores in object 2.

My aim is to retrieve the maximum value of both. If we introduce a third object with 5 scores, I would like to extract 5 as the result.

Is there a way to achieve this using a javascript function?

Your assistance is much appreciated.

Answer №1

To find the simplest solution, you can create a placeholder value and calculate the count before sorting it.

const scoresList = [
  {
    "id": 5,
    "project": 'name project',
    "scores": [
      {
        "id": 7,
        "user_id": 30,
        "implementation_id": 5,
        "score": "12.00",
        "comment": "C'est de la merde, ça vient d’Anthony."
      },
      {
        "id": 10,
        "user_id": 31,
        "implementation_id": 5,
        "score": "15.00",
        "comment": "Super"
      }
    ]
  },
  {
    "id": 6,
    "project": 'name project',
    "scores": [
      {
        "id": 8,
        "user_id": 30,
        "implementation_id": 6,
        "score": "20.00",
        "comment": "Super!"
      },
      {
        "id": 11,
        "user_id": 31,
        "implementation_id": 6,
        "score": "12.00",
        "comment": "Super"
      },
      {
        "id": 15,
        "user_id": 36,
        "implementation_id": 6,
        "score": "10.00",
        "comment": "Super"
      }
    ]
  }
];

for(var i = 0; i < scoresList.length; i++){
   //create a dummy variable scoreCount
    scoresList[i].scoreCount = 0;
    if(scoresList[i].scores){
              scoresList[i].scoreCount = scoresList[i].scores.length;
    }

}
scoresList.sort(function(a, b){ 
    return b.scoreCount - a.scoreCount
});

console.log(scoresList[0]); //This will provide the highest count score

Answer №2

When tackling these tasks face-to-face, I believe that using pure JS is the way to go.

If we assume that the JSON data is stored in a variable called scores:

const groups = scores.map(item => item.scores)

const lengths = groups.map(set => set.length)

const max = Math.max(...lengths)

I find this approach quite elegant (at least in my opinion).

A quick note:

To retrieve a "flat" object containing the results, you can use the following method:

const flatResults = Array.prototype.concat.apply([],scores.map(item => item.scores)))

Answer №3

You have the option to use the map method to transform the scores into an array of arrays containing numbers:

data.map(item=>item.scores.map(x=>x.score).map(Number))

Afterwards, you can apply another map operation in combination with the reduce function to determine the highest score within each sub-array:

.map(scores=>scores.reduce((result,score)=>Math.max(result,score),0))
. This process will yield the highest score for each data item.

If your preference is to find the overall highest score, you can flatten the array and then perform a reduce operation:

.flat().reduce((result,score)=>Math.max(result,score),0)

const data = [{"id":5,"project":"name project","scores":[{"id":7,"user_id":30,"implementation_id":5,"score":"12.00","comment":"C'est de la merde, ça vient d’Anthony."},{"id":10,"user_id":31,"implementation_id":5,"score":"15.00","comment":"Super"}]},{"id":6,"project":"name project","scores":[{"id":8,"user_id":30,"implementation_id":6,"score":"20.00","comment":"Super!"},{"id":11,"user_id":31,"implementation_id":6,"score":"12.00","comment":"Super"},{"id":15,"user_id":36,"implementation_id":6,"score":"10.00","comment":"Super"}]}];


console.log(
  'highest per data item:',
  data.map(item=>item.scores.map(x=>x.score).map(Number))
    .map(scores=>scores.reduce((result,score)=>Math.max(result,score),0))
);

console.log(
  'highest over all:',
  data.map(item=>item.scores.map(x=>x.score).map(Number))
    .flat().reduce((result,score)=>Math.max(result,score),0)
);

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

The React lifecycle method componentDidMount is failing to execute

In my React application, I have the following route setup: <Route path={`${this.props.match.path}horoskop`} render={() => <HoroscopeController horoscopeService={this.horoscopeService} fortuneTellerService={this.fortuneTell ...

Is there a way to speed up the processing time of parsing a 34Mb file using JSON.parse, which currently takes

Our app is currently in the development stage with a database containing approximately 4000 recipes. To save space, we have chosen to store the recipes in one locale during initial download. However, users have the option to switch locales within the app&a ...

Discovering objects on a JavaScript webpage using Selenium

Looking to automate some searches for myself, but running into an issue. Here is the website in question: Struggling to locate the search bar using the program, and unsure why. driver = webdriver.Firefox() driver.get('https://shop.orgatop.de/') ...

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

Is it possible to load babel-polyfill using <script async> tag?

I have created a modal dialog on my webpage that appears when certain interactions occur. Utilizing React, I used webpack to generate a compact bundle that can be added to my page using a script tag. Since it incorporates Generators and needs to support ...

Using yargs to pass parameters/arguments to a Node script through an npm script

Is it feasible to retrieve a key from yargs when utilizing as an npm script argument? A user inputs in the OSX terminal: npm run scaffold --name=blah which triggers in package.json: "scaffold" : "node ./scaffold/index.js -- " This leads to const yar ...

What could be causing the dropdownlist value not to be selected or checked while using "Select2.js"?

1-Description I have implemented a select2 filter for a dropdown list in my project. (Tools used: Bootstrap 5 & .Net 7.0 Core) When I choose a client name and click submit, an error occurs stating that the 'clientId' is null (indicating no ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

Enhance Your Jekyll Site with the Minimal Mistakes Theme Plugin

Hi there! I'm relatively new to website programming and could really use some assistance. I've been attempting to integrate the jekyll-lunr-js-search (https://github.com/slashdotdash/jekyll-lunr-js-search) into the minimal-mistakes theme, but I&a ...

Retry an Ajax request immediately after a timeout without having to wait for the full

I am attempting to resend an AJAX request every 5 seconds if there is an issue, but when I simulate an offline connection with Chrome, the AJAX request doesn't wait 5 seconds between each attempt and keeps getting called continuously. What could be c ...

The prompt "npm run build" command resulted in a 126 Vercel exit status

While attempting to upload my website with Webpack to Vercel from the repository, I encountered an error during the build process: Skipping build cache, deployment triggered without cache. Cloning completed: 2.089s Running "vercel build" Vercel CLI 31.2.3 ...

Steps for displaying a customized view within an NPM module:

Given that pushAsset prohibits loading external resources, I am interested in displaying this template/script from my NPM module: views/tag.html <script async src="https://www.googletagmanager.com/gtag/js?id={{ data.gid }}"></script> NPM mod ...

What sets apart "React.useState setter" from "this.setState" when updating state?

After clicking on the button in AppFunctional, the component fails to update even though the state has changed. However, everything works fine in AppClass. In both cases, we are mutating the original state with "push", but I'm struggling to understan ...

Using jQuery's .remove() function removes all of the children from the container, rather than just one at

For my latest project, I am focused on creating a seamless full-page transition using AJAX calls. The challenge I'm facing is removing content from the DOM when loading in a new page. Despite adding a unique class or ID to the element, the .remove() f ...

Send a Date Object through an Event Emitter to be used in a Date Picker

I created a personalized Date Picker Child Component, and when the onDateChange event occurs, I intend to send an event to the parent component. @Output() selectedDateChange = new EventEmitter<Date>(); onDateChange($event) { this.selectedDateCha ...

Do you mean using a JSON object as a value?

When creating a JSON object where the value itself is an object, what is the correct way to write it? var data ='{"phone":{"gtd": "080"}}'; OR var data ='{"phone":"{gtd: 080}"}'; This question may seem straightforward. I am curious ...

AngularJS ng-repeat: displaying a list of filtered outcomes exclusively

I currently have a ng repeat that loops through a set of results. <a class="list-group-item" href="#trip/{{trip.id}}/overview" ng-repeat="trip in trips | filter:search | limitTo:-15"> Basically, as I enter more text into my input field, the list sh ...

Is there a way to extract the content length from the raw DraftJS data?

I have a system where I am storing the data from my DraftJS editor in my database as a JSON string by passing it through convertToRaw(editorState.getCurrentContent()). For example, this is how the stored data looks like in the database: {"blocks": [{"key ...

AngularJS view does not wait for the completion of $http.get request

Within my controller, the code snippet below is present... $scope.products = dataService.getJsonData(); console.log($scope.products); The corresponding code in my dataservice is as follows: .service('dataService', function ($http) { t ...

Generate a dynamic file import loop within a React application

Suppose I have a directory containing several .md files: /static/blog/ example_title.md another_example.md three_examples.md and an array that includes all the titles: const blogEntries = ["example_title", "another_example", "three_examples"] In ...