Locate the indices of several maximum values within an array

Here is an array for reference:

var exampleArray = [10, 67, 100, 100];

The goal is to identify the indexes of the maximum values in the array.

The existing function currently locates only one index:

function findMaxIndexes(arr) {
      var max = arr[0];
      var maxIndexes = [0];
      for (var i = 1; i < arr.length; i++) {
          if (arr[i] > max) {
              maxIndexes = [i];
              max = arr[i];
          } else if (arr[i] === max) {
              maxIndexes.push(i);
          }
      }
      return maxIndexes;
 }

To update the function to return an array of max indexes, modify it as follows:

When used with the example array provided earlier, the modified function should return:

[2, 3].

Answer №1

To efficiently keep track of multiple indices instead of just one, consider implementing the following code snippet:

function findMaxIndices(arr) {
    var max = -Infinity;
    var maxIndices = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === max) {
          maxIndices.push(i);
        } else if (arr[i] > max) {
            maxIndices = [i];
            max = arr[i];
        }
    }
    return maxIndices;
 }

Answer №2

This is my approach:

let numbers = [5, 34, 76, 98],
      max = Math.max(...numbers),
  indexMax = numbers.reduce((prev, curr, i, arr) => curr == max ? prev.concat(i) : prev,[]);
console.log(indexMax);

Answer №3

const findIndexOfMaxValue = (arr) => {
    const maxVal = Math.max(...arr);
    
    const indexes = [];
    arr.forEach((num, index) => {
        if (num === maxVal) {
            indexes.push(index);
        }
    });
    
    return indexes;
}

const numbers = [5, 10, 15, 10];
console.log(findIndexOfMaxValue(numbers));

Answer №4

After reviewing this comparison of runtimes, I suggest implementing an optimized for-loop to search for the max indices:

function max(arr) {
  var max = -Infinity, indices = [];
  for (var i = 0; i < arr.length; ++i) {
    if (arr[i] < max) continue;
    if (arr[i] > max) {
      indices = [];
      max = arr[i];
    }
    indices.push(i);
  }
  return indices;
}

console.log(max([10, 67, 100, 100])); // [2, 3]

Starting with the comparison arr[i] < max is beneficial as it is true most of the time, allowing us to move to the next iteration with only one array access and comparison on average.

Runtime comparison of the different suggested algorithms:

Based on https://jsfiddle.net/jv1z29jm/2/ - feel free to make updates.

  • Chrome (48):

    max_indexOf x 15,381 ops/sec ±2.94% (87 runs sampled)
    max_reduce x 2,909 ops/sec ±2.63%(86 runs sampled)
    max_forloop x 119,964 ops/sec ±1.80% (87 runs sampled)
    max_forloopOptimized x 165,581 ops/sec ±1.50% (87 runs sampled)
    Fastest is max_forloopOptimized
    
  • Firefox (46):

    max_indexOf x 56,456 ops/sec ±0.74% (67 runs sampled)
    max_reduce x 74,959 ops/sec ±0.86% (65 runs sampled)
    max_forloop x 73,223 ops/sec ±24.75% (58 runs sampled)
    max_forloopOptimized x 84,567 ops/sec ±9.99% (61 runs sampled)
    Fastest is max_forloopOptimized
    

Answer №5

Utilizing JS's Reduce method can be beneficial for solving this particular task.

// Function to find the maximum value in an array
var maxArrSingle = function(arr) {
  return arr.reduce(
    function(acc,val){
      return Math.max(acc,val);
    },
    -Infinity);
}

// Function to find indices where array values are at the maximum
var maxArrIndexes = function(arr) {
  var max = maxArrSingle(arr);
  return arr.reduce(function(acc,val,idx) {
    if (val >= max) acc.push(idx);
    return acc;
  },[]);
}

// Demos
var arr = [10, 67, 100, 100];
console.log(maxArrIndexes(arr));

var arr = [-10, -67, -100, -100, -4000, -9, -90, -90 ];
console.log(maxArrIndexes(arr));

var arr = [];
console.log(maxArrIndexes(arr));

var arr = [0];
console.log(maxArrIndexes(arr));

var arr = [0,0];
console.log(maxArrIndexes(arr));

Answer №6

Here is a simple solution for finding the maximum value in an array and then returning the indexes of all occurrences of that max value.

function findMaxIndexes(arr){

var maxValue = Math.max(...arr);
var maxIndexes = [];

for(let i = 0; i < arr.length; i++){
if(arr[i] === maxValue){
maxIndexes.push(i);
}
}
return maxIndexes;
};

var numbers = [8, 45, 94, 94];
console.log(findMaxIndexes(numbers));

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

javascript creating unique model instances with mongoose

I've searched through related posts without finding exactly what I need. Currently, I am working on building a backend rest API and conducting tests to collect data. Each test has its own model which is associated with collections in the database. T ...

What steps should I take to create an object that can be converted into a JSON schema like the one shown here?

I'm facing a rather simple issue, but I believe there's something crucial that I'm overlooking. My objective is to iterate through and add elements to an object in order to generate a JSON structure similar to the following: { "user1": ...

The table row dissolves instead of disappearing for a specific model

Currently, I am in the process of implementing a live search feature. The aim is to have the elements of a table fade out if they do not match the specified filter and fade in if they do match. Unfortunately, the following code snippet is not achieving thi ...

Looking for a fully customizable event and booking calendar?

Currently, I am searching for a unique event and booking calendar that provides the ability to customize each cell or day with our desired content. While most calendars only allow for inputting events as text, we require a solution that enables us to add ...

AJAX and Python conflict - The requested resource is missing the 'Access-Control-Allow-Origin' header

I am currently developing a unique JavaScript library that has the capability to communicate with a basic Python web server using AJAX. Below is the snippet for the web server class: class WebHandler(http.server.BaseHTTPRequestHandler): def parse_PO ...

What causes functions operating on mapped objects with computed keys to not correctly infer types?

If you are seeking a way to convert the keys of one object, represented as string literals, into slightly modified keys for another expected object in Typescript using template string literals, then I can help. In my version 4.9.5 implementation, I also ma ...

Get specific choices from a drop-down menu based on its grouping options

Looking for help to extract this data cleanly using code. I was under the impression that there was a method already available that could retrieve this data in the desired format. Here's an example of a multiple select: <select id="xpto" ...

Tips for effectively showcasing the counter outcome amidst the increase and decrease buttons

Currently, I am in the process of learning Angular and have created a component called quantity-component. Within the quantity-component.component.html file, I have implemented 2 buttons for increment (denoted by +) and decrement (denoted by -). The decrem ...

I could use some help understanding how to identify the parent file so I can elevate a state

I'm facing a challenge in lifting up a state so that I can utilize it across various pages. The confusion lies in determining where to reference the states, given the uncertainty regarding the parent location. Since this is my first attempt at designi ...

How to format values in a textarea using AngularJS

Is there a way to address the following issue without replacing \n with other values? A user can input a description for something in a textarea and include line breaks. In the controller, there is a value called description which includes a string ...

issues with search functionality in angular

Just diving into the world of angular and struggling with implementing a 'live search' functionality. I've stored my JSON data as a variable in a JavaScript file and successfully displayed it in the HTML. I also have a 'list' radio ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

Issues with error handling in ExpressJS arise frequently

In the server.js file, towards the very end, there is a block of code that appears to handle errors: app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFunction) { console.log(err); mongoDal ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

Ensuring data validity in Angular 2 before enabling a checkbox

In my form, there is a checkbox for admins to edit user accounts. Each user object includes a boolean value isAdmin. I am trying to prevent users from editing their own account while still allowing them to view the values. However, no matter what I try, I ...

Generate an array of JavaScript objects by converting a batch of JSON objects into objects within a Node.js environment

I am working with a prototype class: function customClass(){ this.a=77; } customClass.prototype.getValue = function(){ console.log(this.a); } and I also have an array of JSON objects: var data=[{a:21},{a:22},{a:23}]; Is there a way to cre ...

Using Slick Carousel alongside Browserify for a seamless integration with CDN jQuery

Despite browsing through all the responses on SO regarding this issue, I still haven't found a solution. In my project, I have jQuery loaded via Google CDN. Additionally, I am using babelify, browserify and browserify-shim in an attempt to make slick ...

How can I place a new ThreeJS child element at the front and center of a scene?

I have been working on a webpage that is inspired by the CSS3D molecules sample from ThreeJS's library. You can check out the original sample here. In my project, I am dynamically creating new nodes (atoms) and attaching them to existing nodes. Once ...

Converting an HTML table to a CSV file with pure JavaScript

I need to implement a CSV download feature on my website that converts the HTML table into downloadable content. While searching for a suitable plugin, I came across resources like http://www.dev-skills.com/export-html-table-to-csv-file/ which uses PHP s ...

AngularJS Custom Navigation based on User Roles

I am currently developing a small web application using angular. My goal is to implement role-based navigation in the app. However, I am facing an issue where the isAdmin function does not seem to be getting called on page load, resulting in only the foo a ...