Javascript如何找到数组中的最大数字,并记录位置

Javascript how to find largest numbers in array, and record positions

本文关键字:数字 位置 记录 何找 数组 Javascript      更新时间:2023-09-26

我想找到最简洁的方法来查找数组中最大数字的索引。例:
var array = [0,6,7,7,7];该函数应返回 [2,3,4]

注意:它与数组中最大值的返回索引不同为什么?在那里,答案只返回最大的答案之一。例如,var array = [0,6,7,7,7]将返回 2 或 4。

更新:相当多的人将此标记为重复问题。不是!我在上面的注释中解释了差异。我在返回数组
中最大值的返回索引中要求的假定答案在哪里我也感到沮丧的是,我的第一个问题几乎立即被否决了。

更新:在返回数组中最大值的索引中找到另一个答案

function findLargestOccurances(){
  //Sort the initial array to make it easier
  var arr = [0,6,7,7,7].sort();
  //The largest element is always at the end
  var largest = arr[arr.length-1];
  //The return array will hold positions of the largest element in the array
  var retArr = [];
  //Find occurances of the largest # in the array
  arr.forEach(function(ele,idx){
    //If the current element is the largest one, record the occurance index
    if (ele === largest)
      retArr.push(idx);
  });
  //Log the return array, open your browsers console to see the result!
  console.log(retArr);
}
findLargestOccurances();

此功能也适用于混乱的元素!我在这里创建了一个代码笔:

http://codepen.io/ShashankaNataraj/pen/WwENLb?editors=1011

这非常接近数组中最大值的返回索引。

但是如果你想得到所有的索引,你可以只迭代数组,当当前项目等于max时,将当前索引推送到argmax数组,直到现在找到的最大数量;或者更新max,当你找到更大的项目时argmax

var max = -Infinity, argmax = [];
for(var i=0; i<array.length; ++i)
  if(array[i] > max) max = array[i], argmax = [i];
  else if(array[i] === max) argmax.push(i);
argmax; // [2,3,4]

试试下面的代码。它将为您提供所需的输出

 var array1=[0,6,7,7,7]; 
 var array2=[]; 
 var i = Math.max.apply(Math, array1);
     
     for (var x = 0; x < array1.length; x++) {
           
           if (array1[x] == i) {
                 array2.push(x);               
                 
           }
        }
    
    var z = array2.toString();
    var_dump(z);