Javascript 返回数组中最大值的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11301438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:22:45  来源:igfitidea点击:

Return index of greatest value in an array

javascriptarraysmax

提问by Stephen

I have this:

我有这个:

var arr = [0, 21, 22, 7];

What's the best way to return the index of the highest value into another variable?

将最高值的索引返回到另一个变量的最佳方法是什么?

回答by Ry-

This is probably the best way, since it's reliable and works on old browsers:

这可能是最好的方法,因为它可靠并且适用于旧浏览器:

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

    var max = arr[0];
    var maxIndex = 0;

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

    return maxIndex;
}

There's also this one-liner:

还有这个单行:

let i = arr.indexOf(Math.max(...arr));

It performs twice as many comparisons as necessary and will throw a RangeErroron large arrays, though. I'd stick to the function.

但是,它会根据需要执行两倍的比较,并且会RangeError在大型数组上抛出 a 。我会坚持这个功能。

回答by traxium

In one line and probably faster then arr.indexOf(Math.max.apply(Math, arr)):

在一行中,可能会更快arr.indexOf(Math.max.apply(Math, arr))

var a = [0, 21, 22, 7];
var indexOfMaxValue = a.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);

document.write("indexOfMaxValue = " + indexOfMaxValue); // prints "indexOfMaxValue = 2"

Where:

在哪里:

  • iMax- the best index so far (the index of the max element so far, on the first iteration iMax = 0because the second argument to reduce()is 0, we can't omit the second argument to reduce()in our case)
  • x- the currently tested element from the array
  • i- the currently tested index
  • arr- our array ([0, 21, 22, 7])
  • iMax- 迄今为止最好的索引(迄今为止最大元素的索引,在第一次迭代时,iMax = 0因为 to 的第二个参数reduce()0reduce()在我们的例子中我们不能省略第二个参数)
  • x- 数组中当前测试的元素
  • i- 当前测试的索引
  • arr- 我们的数组 ( [0, 21, 22, 7])

About the reduce()method (from "JavaScript: The Definitive Guide" by David Flanagan):

关于该reduce()方法(来自 David Flanagan 的“JavaScript: The Definitive Guide”):

reduce() takes two arguments. The first is the function that performs the reduction operation. The task of this reduction function is to somehow combine or reduce two values into a single value, and to return that reduced value.

Functions used with reduce() are different than the functions used with forEach() and map(). The familiar value, index, and array values are passed as the second, third, and fourth arguments. The first argument is the accumulated result of the reduction so far. On the first call to the function, this first argument is the initial value you passed as the second argument to reduce(). On subsequent calls, it is the value returned by the previous invocation of the function.

When you invoke reduce() with no initial value, it uses the first element of the array as the initial value. This means that the first call to the reduction function will have the first and second array elements as its first and second arguments.

reduce() 有两个参数。第一个是执行归约操作的函数。此归约函数的任务是以某种方式将两个值组合或归约为一个值,并返回该归约后的值。

与reduce() 一起使用的函数不同于与forEach() 和map() 一起使用的函数。熟悉的值、索引和数组值作为第二、第三和第四个参数传递。第一个参数是到目前为止减少的累积结果。在第一次调用该函数时,第一个参数是您作为第二个参数传递给 reduce() 的初始值。在后续调用中,它是前一次调用函数返回的值。

当您在没有初始值的情况下调用 reduce() 时,它使用数组的第一个元素作为初始值。这意味着对缩减函数的第一次调用将第一个和第二个数组元素作为它的第一个和第二个参数。

回答by Lanil Marasinghe

Here is another solution, If you are using ES6 using spread operator:

这是另一种解决方案,如果您使用 ES6 使用扩展运算符:

var arr = [0, 21, 22, 7];

const indexOfMaxValue = arr.indexOf(Math.max(...arr));

回答by Kevin

If you are utilizing underscore, you can use this nice short one-liner:

如果你使用下划线,你可以使用这个漂亮的短单行:

_.indexOf(arr, _.max(arr))

It will first find the value of the largest item in the array, in this case 22. Then it will return the index of where 22 is within the array, in this case 2.

它将首先找到数组中最大项的值,在本例中为 22。然后它将返回 22 在数组中的位置的索引,在本例中为 2。

回答by Dan Tao

Unless I'm mistaken, I'd say it's to write your own function.

除非我弄错了,否则我会说是编写自己的函数。

function findIndexOfGreatest(array) {
  var greatest;
  var indexOfGreatest;
  for (var i = 0; i < array.length; i++) {
    if (!greatest || array[i] > greatest) {
      greatest = array[i];
      indexOfGreatest = i;
    }
  }
  return indexOfGreatest;
}

回答by randompast

Another solution of max using reduce:

max 的另一种解决方案reduce

[1,2,5,0,4].reduce((a,b,i) => a[0] < b ? [b,i] : a, [Number.MIN_VALUE,-1])
//[5,2]

This returns [5e-324, -1]if the array is empty. If you want just the index, put [1]after.

[5e-324, -1]如果数组为空,则返回。如果你只想要索引,把它放在[1]后面。

Min via (Change to >and MAX_VALUE):

最小通过(更改为>MAX_VALUE):

[1,2,5,0,4].reduce((a,b,i) => a[0] > b ? [b,i] : a, [Number.MAX_VALUE,-1])
//[0, 3]

回答by Edward Karak

function findIndicesOf(haystack, needle)
{
    var indices = [];

    var j = 0;
    for (var i = 0; i < haystack.length; ++i) {
        if (haystack[i] == needle)
            indices[j++] = i;
    }
    return indices;
}

pass arrayto haystackand Math.max(...array)to needle. This will give allmax elements of the array, and it is more extensible (for example, you also need to find min values)

通过arrayhaystackMath.max(...array)needle。这将给出数组的所有最大元素,并且更具可扩展性(例如,您还需要找到最小值)

回答by ross studtman

EDIT: Years ago I gave an answer to this that was gross, too specific, and too complicated. So I'm editing it. I favor the functional answers above for their neat factor but not their readability; but if I were more familiar with javascript then I might like them for that, too.

编辑:几年前,我对此给出了一个粗俗、过于具体且过于复杂的答案。所以我正在编辑它。我喜欢上面的功能性答案,因为它们简洁,但不是它们的可读性;但如果我更熟悉 javascript,那么我也可能会喜欢它们。

Pseudo code:

伪代码:

Track index that contains largest value. Assume index 0 is largest initially. Compare against current index. Update index with largest value if necessary.

跟踪包含最大值的索引。假设索引 0 最初是最大的。与当前指数进行比较。如有必要,用最大值更新索引。

Code:

代码:

var mountains = [3, 1, 5, 9, 4];

function largestIndex(array){
  var counter = 1;
  var max = 0;

  for(counter; counter < array.length; counter++){
    if(array[max] < array[counter]){
        max = counter;
    }
  }
  return max;
}

console.log("index with largest value is: " +largestIndex(mountains));
// index with largest value is: 3

回答by rodurico

If you create a copy of the array and sort it descending, the first element of the copy will be the largest. Than you can find its index in the original array.

如果创建数组的副本并将其降序排序,则副本的第一个元素将是最大的。比你可以在原始数组中找到它的索引。

var sorted = [...arr].sort((a,b) => b - a)
arr.indexOf(sorted[0])

Time complexity is O(n) for the copy, O(n*log(n)) for sorting and O(n) for the indexOf.

副本的时间复杂度为 O(n),排序的时间复杂度为 O(n*log(n)),indexOf 的时间复杂度为 O(n)。

If you need to do it faster, Ry's answer is O(n).

如果你需要做得更快,Ry 的答案是 O(n)。

回答by mos wen

 var arr=[0,6,7,7,7];
 var largest=[0];
 //find the largest num;
 for(var i=0;i<arr.length;i++){
   var comp=(arr[i]-largest[0])>0;
      if(comp){
   largest =[];
   largest.push(arr[i]);
   }
 }
 alert(largest )//7
 
 //find the index of 'arr'
 var arrIndex=[];
 for(var i=0;i<arr.length;i++){
    var comp=arr[i]-largest[0]==0;
 if(comp){
 arrIndex.push(i);
 }
 }
 alert(arrIndex);//[2,3,4]