4

I found some solutions to get max value of indexes, but how can I get the max value when I have array like this:

myArray = [];
myArray[1] = 10;
myArray[2] = 99;

alert(Math.max(myArray));

I would like to get index of max value. In this case it would be index 2 of value 99.

The result I get now is NaN.alert(Math.max(myArray));

Jon Doe
  • 2,172
  • 1
  • 18
  • 35
user1876234
  • 857
  • 2
  • 14
  • 28
  • You need a loop to run trough the array and compare values. http://stackoverflow.com/questions/2824145/sorting-a-multidimensional-array-in-javascript – user1054844 Apr 07 '15 at 14:03

1 Answers1

4

1. If you only want the first instance:

var arrayMaxIndex = function(array) {
  return array.indexOf(Math.max.apply(null, array));
};

console.log(arrayMaxIndex([1,2,7,2])); //outputs 2

2. If you want all occurrences of the max:

function getAllIndexes(arr, val) {
    var indexes = [], i = -1;
    while ((i = arr.indexOf(val, i+1)) != -1){
        indexes.push(i);
    }
    return indexes;
}

var arrayAllMaxIndexes = function(array){
    return getAllIndexes(array, Math.max.apply(null, array));
}

console.log(arrayAllMaxIndexes([1,2,7,2,7])); // outputs [2,4]

Everyone does ES6 Updates so here is mine:

const arr = [1, 2, 3];
const max = Math.max.apply(Math, arr.map((i) => i));
const maxIndex = arr.indexOf(max);

Also you can achieve the same thing using reduce:

const getMax = (arr) => arr.reduce((acc, item) => (item > acc ? item : acc), arr[0]);
makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76
  • A slight variation is `return array.indexOf(Math.max.apply({}, array));` – Dexygen Apr 07 '15 at 14:10
  • The while loop in getAllIndexes runs arr.indexOf over the rest of the array many times. Here's a simpler for loop the gives the same result but does so more efficiently by only running over the array once: `for (let i = 0 ; i < array.length ; i++) { if (array[i] === val) { indexes.push(i); } }` – Sámal Rasmussen Jan 07 '20 at 12:57
  • Also if you wonder how `Math.max.apply(null, array)` works: https://stackoverflow.com/questions/24541600/how-does-applymath-arrayname-work-javascript – Sámal Rasmussen Jan 07 '20 at 13:02
  • How to get the last max occurrence index? – SDK Nov 08 '22 at 17:20
  • arr.lastIndexOf(Math.max(...arr)) – makeitmorehuman Nov 09 '22 at 12:20