Languages
[Edit]
EN

JavaScript - get index of greatest value in array

0 points
Created by:
Dragontry
731

In this article, we would like to show you how to get the index of the greatest value in an array in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

var numbers = [2, 3, 1]

var indexOfMax = numbers.indexOf(Math.max(...numbers));

console.log(indexOfMax);  // 1

Note:

This solution is not optimal.

 

Practical example

In this example, we present a reusable function that also works in older web browsers.

// ONLINE-RUNNER:browser;

function indexOfMax(array) {
    if (array.length === 0) {
        return -1;
    }

    var max = array[0];
    var result = 0;

    for (var i = 1; i < array.length; ++i) {
        if (array[i] > max) {
            result = i;
            max = array[i];
        }
    }

    return result;
}


// Usage example:

var numbers = [2, 3, 1];

var maxIndex = indexOfMax(numbers);

console.log(maxIndex); // 1

 

See also

  1. JavaScript - max value in array

  2. JavaScript - Math.max() method example

References

  1. Array.prototype.indexOf() - JavaScript | MDN
  2. Math.max() - JavaScript | MDN
  3. Spread syntax (...) - JavaScript | MDN

Alternative titles

  1. JavaScript - return index of greatest value in array
  2. JavaScript - get index of max value in array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join