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));

1

1 Answer 1

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]);
Sign up to request clarification or add additional context in comments.

5 Comments

A slight variation is return array.indexOf(Math.max.apply({}, array));
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); } }
Also if you wonder how Math.max.apply(null, array) works: stackoverflow.com/questions/24541600/…
How to get the last max occurrence index?
arr.lastIndexOf(Math.max(...arr))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.