What is the best way to retrieve the highest value along with its corresponding text or name from a multidimensional

I am working with a multidimensional array called 'dataArray' which has the following structure.

dataArray = [ {name:"Apples", score: 3.5}, {name:"Oranges", score: 3.7}, {name:"Grapes", score: 4.1} ];

My goal is to find the highest score along with its corresponding name from the dataArray.

function playerArray() {

  dataArray = [{
    name: "Apples",
    score: 3.5
  }, {
    name: "Oranges",
    score: 3.7
  }, {
    name: "Grapes",
    score: 4.1
  }];

  for (i = 0; i < dataArray.length; i++) {
    var nameArray = dataArray[0].name;
    var scoreArray = dataArray[0].score;

    var largest = Math.max.apply(Math, scoreArray);

    alert(largest[0].score);
  }
}

When I run the 'playerArray()' function, it raises the following error: test.html:24 Uncaught TypeError: CreateListFromArrayLike called on non-object at playerArray

Answer №1

If you're looking to find the maximum score in an array of objects, you can utilize the powerful Array.reduce() method.

let dataArray = [ {name:"Apples", score: 3.5}, {name:"Oranges", score: 3.7}, {name:"Grapes", score: 4.1} ];

let max = dataArray.reduce((acc,elem) => { return elem.score > acc.score ? elem : acc }, {name: "", score: -1});

console.log(max);

Answer №2

Here is a neat and straightforward method:

dataArray = [ {name:"Apples", score: 3.5}, {name:"Oranges", score: 3.7}, {name:"Grapes", score: 4.1} ];

var maxScore = {name:'',score:0};

for(var i = 0; i< dataArray.length; i++){
  var currElem = dataArray[i];
  var currScore = currElem.score;

  //keep track of highest score so far
  if(maxScore.score < currScore){
     maxScore.name = currElem.name;
     maxScore.score = currElem.score;
  }

}

console.log(maxScore)

You can see a live example here

If you wish to make it more concise, you can do the following:

 if(maxScore.score < currScore){
     maxScore = currElem;
  }

To add elegance and avoid the loop along with some variables, consider utilizing map:

var maxScore = {name:'',score:0};

dataArray.map(function(elem) {
  if (maxScore.score < elem.score) {
    maxScore = elem
  }
});

View a live example using the map approach here

Answer №3

To efficiently find the object with the highest score in a dataset, use an index named maxIndex as shown below:

dataArray = [{
  name: "Bananas",
  rating: 4.0
}, {
  name: "Peaches",
  rating: 3.8
}, {
  name: "Plums",
  rating: 4.3
}];

var maxIndex = 0;
for (i = 1; i < dataArray.length; i++) {
  if(dataArray[maxIndex].rating < dataArray[i].rating)
    maxIndex = i;
}

var maxObject = dataArray[maxIndex];

console.log(maxObject);

Answer №4

This task is incredibly simple with a basic reduction technique. Using the .reduce() function in this way is just like the common example of summing array elements.

totalSum = nums.reduce((x,y) => x+y)

Now, take a look at this:

let items = [ {name:"Bananas", quantity: 5}, {name:"Cherries", quantity: 7}, {name:"Peaches", quantity: 4} ],
 maxItem = items.reduce((x,y) => x.quantity > y.quantity ? x : y);
console.log(maxItem);

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

How to use the handleChange() function in React with various state properties

Explaining a bit about the handleChange function, which takes the name of the state element to be associated with it. Is there a specific reason why it has to be structured like this: handleInputChange(property) { return e => { this.setSta ...

ng-include does not incorporate a partial view

I am facing an issue with ng-include as this code is not functioning properly and I'm unable to identify the error. <select name="select" id="select" class='input-large' ng-model="selectedbien"> ...

What is the process for integrating GitHub repository code into my client-side JavaScript application?

I am attempting to incorporate the GitHub repository "zipcelx" into my client-side JavaScript, but all I see is an option to download it from npm, which I do not understand. It would be helpful if someone could explain how a module meant for client-side us ...

Unhook, add at the beginning, and set requirements jQuery

There are two clickable div elements that can switch classes when clicked. If the first one contains "1", it will be given a class of "active". If the second one contains "2", it will have the class "active" while removing the class from the first one. &l ...

Transmitting an array within the POST request payload

My goal is to send an array to my Node/MongoDB server using an AJAX POST request, along with other variables in the body. Check out the client side JS code below: function setupForm(){ $("#add").submit(function(event) { event.preventDefault() ...

String constant without an ending

My Description has a single quote character('). How can I make sure it doesn't break the code? <a href='javascript:select("<%= pageBean.replace(list.getColumn(0), "'", "'") %>", "<%= pageBean.replace(list.getColumn(1), ...

Store database query results in an array, consolidating all user_id entries into a single array element

I currently have a database with a user entry TABLE - where I query out something like: user_id: 1 user_point: 20 user_id: 1 user_point: 50 user_id: 2 user_point: 10 This data is saved into an array, which looks like this: $highscoreData = array(); w ...

"Common Errors Encountered When Running 'npm start'

Each time I attempt to initiate my react project, it presents me with these errors npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\Mohamed Badrawy\Desktop\reactjs-basics-master\package.json npm ERR! errno -4058 n ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

Tips for automatically closing a dropdown menu when it loses focus

I'm having some trouble with my Tailwind CSS and jQuery setup. After trying a few different things, I can't seem to get it working quite right. In the code below, you'll see that I have placed a focusout event on the outer div containing th ...

Encountered an issue with the response - SyntaxError: Unexpected end of input while utilizing the 'no-cors' mode

I attempted a Fetch call in ReactJS to a REST-API and am trying to manage the response. The call is successful, as I can see the response in Chrome Dev Tools: function getAllCourses() { fetch('http://localhost:8080/course', { method: 'P ...

Incorporating Javascript into a <script> tag within PHP - a step-by-step guide

I am trying to integrate the following code into a PHP file: if (contains($current_url, $bad_urls_2)) { echo '<script> $('body :not(script,sup)').contents().filter(function() { return this.nodeType === 3; ...

Exploring the magic of Rails array columns with Postgres

I'm encountering an issue with my model that has an array column called 'box_ids'. Is there a way to display a field for each value in the array within my view, while also including three extra empty fields for adding new values to the array ...

Guide on assigning JSON response values to TypeScript variables in Angular 4

I'm just starting with Angular 4 and I'm attempting to retrieve a JSON value using http.post. The response I'm receiving is: {"status":"SUCCESS"} component onSubmit(value: any) { console.log("POST"); let url = `${this.posts_Url}`; t ...

Implement admin-on-rest framework within my current project

Currently, I am in the process of building an admin-tool website using Material UI. To handle asynchronous calls, I have integrated Redux Saga into my project for calling services. The Admin on Rest framework offers some beneficial components like the Data ...

Receiving a blank array from the firestore database

I have written a code for the LeftBar Component where I am trying to retrieve data stored in the "contacts" document in Firebase. However, I am getting an empty array and I'm not sure why this is happening. Additionally, I would like to know how to ac ...

Leveraging URL parameters within node.js and Express

Having no prior experience with node, I decided to delve into the Express project in VS2019. My goal was to create master/detail pages with a MongoDB data source. In my pursuit, I configured three routes in /routes/index.js. //The following route works as ...

Having trouble with linking an external JavaScript file inside the head tag?

I've connected my script.js file to my index.html file, and both files are located in the same directory. I initially linked the script.js file in the <head> section, but it wasn't working as expected. Upon checking the console, I encounter ...

Crafting dynamic objects with THREE.JS

I am working with a JSON configuration that looks like this: { shape:[ 'SphereGeometry', [7, 16, 16] ] } My goal is to load a model using the following code: new THREE[shape[0]].apply( this, shape[1] ) However, it seems that using "new" and " ...

Encountering a 403 error while attempting to install Meteor with npm using the command npm install -

Following the installation instructions provided on the official Meteor website at , I encountered an error while trying to install Meteor using the command "npm install -g meteor". Here is the detailed error message: os  win 10 pro node -v  v14.15.1 n ...