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

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...

Error encountered during AJAX POST request: NETWORK_ERR code XMLHttpRequest Exception 101 was raised while using an Android device

Here is the ajax post code that I am using: $.ajax({ type: "POST", url: "http://sampleurl", data: { 'email':$('#email').val(), 'password':$('#password').val(), }, cache: false, ...

Replace all occurrences of $regex in Node.js with the json data format

Here is a JSON example var json= { name: { '$regex': /^Amer$/i }, 'countries.name': { '$regex': /^UNited states$/i } } I am looking to reformat it using either lodash or string/json replace method to achieve the following st ...

Leveraging configuration files in AngularJS

I'm working on an Angular application that communicates with a Node.js backend Express application. I am using a config file to store environment variables for my Node app. Here's how I access the config file in my Node app: index.js var port = ...

What could be causing the 403 Error when using Blogger API with AngularJS?

I'm relatively new to working with 3rd Party APIs and I'm currently exploring how to integrate Blogger's API into my AngularJS website to create a blog feed feature. After setting everything up, I've made a request and received a 200 s ...

Is AjaxMin's EvalTreatment changing the game for JavaScript minification?

While minifying my project using the AjaxMin.dll with the default settings on every build/deployment, I ran into a problem. One of our third-party JavaScript files contains an eval statement that references variables or parameters which, when minified, cau ...

The $.post method is malfunctioning

I am experiencing an issue where the onchange function is working properly, but the $.post function is not functioning as expected. Below is the HTML code snippet: <input type="checkbox" id="chk" value="3" onchange="checkradio(this.value)"/> Here ...

The border of the Material UI Toggle Button is not appearing

There seems to be an issue with the left border not appearing in the toggle bar below that I created using MuiToggleButton. Any idea what could be causing this? Thank you in advance. view image here view image here Just a note: it works correctly in the ...

leveraging third party plugins to implement callbacks in TypeScript

When working with ajax calls in typical javascript, I have been using a specific pattern: myFunction() { var self = this; $.ajax({ // other options like url and stuff success: function () { self.someParsingFunction } } } In addition t ...

The split function in JavaScript is exhibiting some unusual behavior

There is something wrong with my code challenge1 = () => { var data = fs.readFileSync('santa21.txt', 'utf8'); data = data.toString(); dataSplit = data.split(' ') console.log(dataSplit); }; challenge1(); The result of the ...

Input a new value into the registration field to update it

My current task involves adding a new text field to a React form using a button. I need this new input text field to be able to store data on a register. How can I go about setting this property? Typically, when creating a text field, you would utilize co ...

A guide on automating the html5 color picker using input type="color" in selenium webdriver

When interacting with an HTML color input element, a color picker window pops up that prevents viewing the DOM. I am looking for a solution to either select a color and close the window or enter a hex code in the popup's text box. Can anyone provide m ...

What is the reason for the undefined output of this verified JSON Web Token (JWT)?

I've been working on decoding a JWT id_token using the libraries jwks-rsa and jsonwebtoken, however, the result keeps coming back as undefined. I understand that this issue is related to callbacks and the need to wait for a response from the getKey f ...

I've encountered an issue when attempting to use innerHTML for DOM manipulation

I've been attempting to remove a specific list item <li> from the inner HTML by assigning them proper IDs. However, I'm encountering difficulties in deleting it. How can I delete these list items after clicking on the cross button? Feel fr ...

AngularJS - directive template is not being compiled correctly

I am facing an issue with AngularJS. .directive('field', ['$routeParams', function($routeParams){ return { restrict: 'E', compile: function(tElement, tAttributes) { var template ...

Unexpected unhandled_exception_processor in Google Chrome

I keep encountering a strange uncaught exception handler in Google Chrome. After updating all follow buttons to download JavaScript asynchronously, I noticed an error in the content.js file mentioned in the exception message which advises against polluting ...

Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday! Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format. I am facing an issue with exporting all the visual content of a DIV in either PDF or image ...

Results don't align with search parameters

const searchClientes = (event) => { if (event.target.value === '') { getClientes(); return; } else { const searchTerm = event.target.value; const filteredClients = clientes.filter(cliente => { return cliente.nome ...

Localization for Timeago JS Plugin

Currently, I have integrated the jQuery TimeAgo plugin into my project and included the following code snippet for localization in Portuguese: // Portuguese jQuery.timeago.settings.strings = { suffixAgo: "atrás", suffixFromNow: "a partir de agora", ...

Maximizing Efficiency: Utilizing a Single jQuery Function to Retrieve Specific Values

I have a webpage with select menus for choosing user type, minimum age, and maximum age. I want to select options and send values as an object array to ajax. Initially, the getAjax function is working when the page loads. However, it stops working when I c ...