Retrieve the highest value indexes from a three-dimensional array with JavaScript

In my dataset, I have an array structured like this:

[34, 12, 56]
[100,125,19]
[30,50,69]

The highest value in this array is 125, so the index [1,1] is returned. This means that 125, the highest value, can be found in row 1, column 1.

To determine the index of the maximum value in an array, I used the following code:

var a = [0, 21, 22, 7, 12];
var indexOfMaxValue = a.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : 
iMax, 0);
document.write("indexOfMaxValue = " + indexOfMaxValue); // prints 
"indexOfMaxValue = 2"

Answer №1

My method involves flattening all arrays for easier management, identifying the highest number and its position, and determining its final location through mathematical calculations. This approach simplifies the calculation by using a single array.

const arr = [[34, 12, 56], [100,125,19], [30,50,69]];
const arr2 = [0, 21, 22, 7, 12];

function findHighest(arr) {

  // Calculate the number of columns
  const cols = arr.length;

  // Flatten the arrays
  const tempArr = arr.flatMap(el => el);

  // Find the highest number in the array
  const max = Math.max.apply(null, tempArr);

  // Determine the index of the highest number
  const indexMax = tempArr.findIndex(el => el === max);

  // Calculate the remainder when dividing the index by the number of columns
  const mod = indexMax % cols;

  // Output the final array
  return [Math.floor(indexMax / cols), mod];
}

console.log(findHighest(arr))
console.log(findHighest(arr2))

Answer №2

This code snippet demonstrates a solution to finding the maximum value in a two-dimensional array. However, there may be alternative approaches worth considering:

const array = [
    [34, 12, 56],
    [100, 125, 19],
    [30, 50, 69]
];
let maxValue, maxIndex;
array.forEach((innerArray, i) => {
    innerArray.forEach((value, j) => {
        if (i === 0 && j === 0) {
            maxValue = value;
            maxIndex = [i, j]
        } else {
            if (maxValue < value) {
                maxValue = value;
                maxIndex = [i, j];
            }

        }

    });
});

console.log("Index of Maximum Number:", maxIndex);

Answer №3

For those looking for a 2D solution, give this a try. It should be able to handle arrays of varying lengths dynamically. Also, it can be expanded with a new forEach loop to accommodate additional dimensions.

[100, 125, 19],
[30, 50, 69]];

maxIndex = [-1, -1];
maxElem = 0;
input.forEach(function(arr, row) {
    console.error(row);
    arr.forEach(function(e, col) {
    if( maxElem <= e ) {
        maxElem = e;
        maxIndex = [row, col];
    }
  })
})

console.log(maxIndex)

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

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...

Customizing the appearance of Jquery UI Accordion Headers

Trying to integrate the JQuery UI accordion into my JQuery UI modal dialog has been causing some alignment issues. Despite following code examples found online, such as http://jsfiddle.net/eKb8J/, I suspect that the problem lies in CSS styling. My setup i ...

Is it possible to use the same HTML select/dropdown menu for multiple rows in a table?

I am working with an HTML table that usually has between 10-30 rows, each containing a column for "item name". The drop down menu consists of about 75 products to choose from. In order to reduce the page size, I want to use a single drop down list for all ...

Creating a dynamic multi-item carousel with Materialize (CSS) cards using data from a loop - here's how!

Using a for loop, the following code generates a list of cards. These cards are intended to be displayed in a carousel with 4 cards visible at once, and a next arrow button allows users to navigate through the next set of 4 cards. Materialize cards have ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

"Invalid: string path required" (version 5.10.0)

There's this file (a large bundle of a couple of JS files) that used to work perfectly with browserify (version 5.10.0) until just recently, but now it's not cooperating. Here's the command I'm using: $ browserify index.js -o dist/out ...

Managing and enumerating array elements in an angular.js controller

In my Angular application, I am working with an array of objects that each contain a "ready" field storing a timestamp. My goal is to determine the count of objects where the "ready" timestamp is earlier than the current time. How can I achieve this? This ...

Issue: Inability to scroll on div overflow section

My website consists of one static page with an HTML and CSS file. Oddly enough, when testing the page and inputting content into a multiline textarea until it overflows, the browser fails to display a scrollbar. Despite inspecting the div with the id &apos ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Problems Arising from the Combination of Django and External JavaScript

I am currently working on a project that uses Django 1.11 and JavaScript, but I am encountering an issue. The JavaScript code works fine when run within the HTML file, as it successfully loads the JSON data. However, when I move everything to the static fo ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

Navigating through various arrays within objects on a JSON API with JavaScript: A walkthrough

I am currently working on fetching and displaying data from an API. The specific data I am interested in is located within the 'equipments' array. You can see an example of this array in the image linked below: https://i.sstatic.net/QeBhc.jpg M ...

Refresh the dropdown menu selection to the default option

My HTML dropdown menu includes a default option along with dynamically generated options using ng-options. The variable dropdown is bound to the dynamic options, not the default one. <td> <select ng-model="dropdown" ng-options="item as item.n ...

Mastering the art of concurrent Ajax requests using jQuery for an advanced Posting and Commenting system

In my Asp.net MVC project, I have successfully implemented a post and comment mechanism. The posts and comments are stored in different tables in the database. Additionally, using Ajax requests with jQuery, I can retrieve comments from the database and dis ...

Execute function when image finishes loading (Internet Explorer)

Is there a way to execute a method once an image is completely loaded, considering that the .load function doesn't work for images in Internet Explorer? Below is the code snippet in question: <img ref="image" :src="src" :alt="alt" @load=" ...

An error in TypeScript has occurred, stating that the type 'IterableIterator<any>' is neither an array type nor a string type

Hey there! I'm currently working on an Angular project and encountering an error in my VS Code. I'm a bit stuck on how to fix it. Type 'IterableIterator<any>' is not an array type or a string type. Use compiler option '- ...

What is the best way to retrieve AWS secret values using JavaScript?

Having recently started using AWS, I have been able to manually obtain the secret I need. However, when attempting to utilize the code snippet provided by AWS to retrieve the secret value, all my attempts result in undefined. Can someone please point out ...

Having trouble passing a JavaScript variable through AJAX requests

In this particular script, I am encountering an issue where the variable "encrypted" is expected to be sent via ajax to upload.php, however I am unable to achieve this. Oddly enough, if I substitute the "encrypted" variable with another variable in the a ...

The result of the $.post() request is back

In my current code, I am using a jQuery $.post function like this: $.post('/test', json_data, function(data) { result = data }); This function is being used in a validation process where the return value (data) contains either true or false ...

What is the best way to determine the size of a returned element in React?

How can I determine if the description of {book.volumeInfo.description} is empty or not? If the length of {book.volumeInfo.description} is greater than zero, display it; otherwise, show "Book without description". I am unsure of the correct way to get the ...