Determine the array with the highest value by comparing multidimensional arrays in JavaScript

I have a multidimensional array with names and corresponding integer values. I want to compare the integer values within each nested array to find and return the one with the highest value.

var nums = [
    ['alice', 'exam', 60],
    ['dave', 'quiz', 85]
];

What is the best way to iterate through the arrays in the "nums" array and identify the array with the greatest integer value?

Answer №1

An alternative method to achieve this is by using the reduce function in JavaScript. Here's an example:

var data = [
    ['alice', 'test', 80],
    ['bob', 'quiz', 92],
    ['carol', 'exam', 75],
    ['dave', 'homework', 88]
];

var highestScore = data.reduce((prev, current) => prev[2] > current[2] ? prev : current);
console.log(highestScore);

You can also access a working demonstration on JSFiddle here


Keep in mind that when using reduce() without an initial value, the first item becomes a and the second item becomes b in the first iteration.

Answer №2

let maxNumber = totals.reduce((prev, cur) => prev[2] > cur[2] ? prev : cur, [0,0,0]);

Answer №3

Let's use the reduce method to find the highest total in the array:

var result = totals.reduce((p, c) => {
    return p[2] > c[2] ? p : c;
});

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

Extract data from a JSONArray that includes both primitive values and complex objects

I received a JSON response that has the following structure: { "response":[ "Some number (for example 8091)", { "Bunch of primitives inside the first JSONObject" }, { "Bunch of primitives inside the second JSON ...

How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined { "items": [ { ...

Submitting form by clicking a link on the page

To submit a POST request with "amount=1" without displaying it in the URL, I need the site to send this request when any link on the site is clicked. This JavaScript code achieves that with a GET request: window.onload = function () { document.body.oncli ...

Mixing success and error states can lead to confusion when using jQuery and Express together

I've been struggling with a simple question that's been on my mind for quite some time. Despite my searches, I haven't found a similar query, so I apologize if it seems too basic or repetitive. The scenario involves an API route (Express-ba ...

Error: The object does not have the property createContext necessary to call React.createContext

I'm currently exploring the new React Context API in my app. I've also implemented flow for type checking. However, when I add // @flow to a file that contains the code: const MyContext = React.createContext() An error pops up stating: Cannot ...

Switch or toggle between colors using CSS and JavaScript

Greetings for taking the time to review this query! I'm currently in the process of designing a login form specifically catered towards students and teachers One key feature I'm incorporating is a switch or toggle button that alternates between ...

The array is failing to pass through ajax requests

Here is the JavaScript code snippet for making an AJAX call. In this scenario, the code variable is used to store a C program code and then pass it on to the compiler.php page. function insert(){ var code = document.getElementById("file_cont").val ...

Trigger a function in jQuery when the DOM undergoes changes

Up until now, I have been utilizing livequery which has served its purpose. However, it tends to slow down the page browsing experience, so I am in search of an alternative solution. I have a function that performs ajax on elements with a specific class l ...

Adjusting the width of the rail in Material UI's vertical Slider component in React

After attempting to adjust the width and height of the rail property on the material ui slider I obtained from their website demo, I have encountered an issue with changing the thickness. import React from "react"; import { withStyles, makeStyles } from " ...

Is it possible for an ul to be displayed beneath a white section within an li

I am working on a JQuery carousel that is displaying correctly, but I want to make a small adjustment to the content: <li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-1 jcarousel-item-1-horizontal" style="float: left; list-style: none ...

Accessing 'this' within a Firebase callback function

As I work on my Vue.js application, I encounter an issue with fetching data from Firebase when the component mounts. While I am able to successfully retrieve the data, I am struggling to write it into a Vue.js data property. I have tried using this.propert ...

Use the map function to find the highest number within each array

function each(collection, func) { if (Array.isArray(collection)) { for (var i = 0; i < collection.length; i++) { func(collection[i], i); } } else { for (var key in collection) { func(collection[key], key); } } } functi ...

How to modify the value of an attribute in a HTML element

I have a photo that I am using with an Image Map in my HTML document Recently, I incorporated some Bootstrap elements to my page, but to make a long story short, I am looking to dynamically change the coordinates of the map areas based on the position of ...

I must develop a custom function that generates a pure JavaScript string with the 'name' index and includes all the 'props'

My code is almost correct, but instead of returning a ':' in the Json result as desired, it returns a ','. Is there a way to achieve the desired result without modifying the JSON string like I did with the "replaces"? I am searching fo ...

JavaScript will continue to process the submit to the server even after validation has been completed

My current challenge involves implementing form validation using JavaScript. The goal is to prevent the form from being sent to the server if any errors are found. I have made sure that my JavaScript function returns false in case of an error, like so: ...

What is the best way to call the app.js function from an HTML page in an Express.js environment

Is there a way to trigger the function init() { // } located in app.js from an HTML page? <a href='javascript:init();'> Trigger init </a> The issue with the code above is that it searches for function init() only on the client side ...

Tips for maintaining i18n locale slugs and ensuring i18n consistency when reloading in Next.js

I'm currently utilizing next-translate. The default recognition of my routes is as follows: /about <--- /de/about /es/about However, I would like to set a specific locale for all paths: /en/about <--- /de/about /es/about Below is ...

Double injection of Redux-saga

I've encountered a strange issue with my redux-saga - it's being called twice instead of just once. Here is the action that triggers the saga: export function createRequest (data) { return { type: CREATE_REQUEST, payload: {data} }; ...

Successively linking promises together within a for-each iteration

How can I ensure that a foreach loop is synchronous in AngularJS var articles = arg; articles.forEach(function(data){ var promises = [fetchImg(data), fetchUser(data)]; $q.all(promises).then(function (res) { finalData.push(res[1]); ...

I have a query regarding the process of filtering data, specifically in the context of

When working with express and mongoose, I often encounter complex queries. As a workaround, I typically retrieve objects by their ID like this: const ticketObj = await Ticket.findById(ticketId); I then use JavaScript's filter method to further narro ...