查找数组中多个最大值的索引 [英] Find indexes of multiple max values in array

查看:75
本文介绍了查找数组中多个最大值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例数组:

var arr = [10,67,100,100];

我想找到数组最大值的索引。

I want to find the indexes of the maximum values in the array.

此函数仅找到一个索引:

This function finds only one index:

function max(arr) {
      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;
 }

如何修改它以返回最大索引数组?在上面的示例数组中,它应返回

How can I modify it to return an array of max indexes? In the example array above, it should return

[2,3]

推荐答案

您需要跟踪所有索引,而不是仅跟踪一个索引。试试看:

Instead of keeping track of just one index, you'll need to keep track of all indices. Give this a try:

function max(arr) {
    var max = -Infinity;
    var maxIndices = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === max) {
          maxIndices.push(i);
        } else if (arr[i] > max) {
            maxIndices = [i];
            max = arr[i];
        }
    }
    return maxIndices;
 }

这篇关于查找数组中多个最大值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆