Kaziko
Kaziko

Reputation: 142

Get random element from array based on highest value

I am using this code to get key from array with highest value

function getHighest(o){
    var vals = [];
    for(var i in o){
        vals.push(o[i]);
    }

    var max = Math.max.apply(null, vals);

    for(var i in o){
        if(o[i] == max){
            return i;
        }
    }
}

but sometimes there are more results in array with the same highest value e.g.

item1 = 4
item2 = 2
item3 = 1
item4 = 4

and code I am using returns only first result (item1). So my goal is to get key with highest value but in case there are more elements with the same highest value choose randomly one of them.

Upvotes: 3

Views: 340

Answers (3)

Abdullah Shoaib
Abdullah Shoaib

Reputation: 464

You can do it like

 function getHeighest(arr){
    var temp_max = Math.max.apply(null,arr);
    for(var i in arr){
      if(arr[i] == temp_max){
        return i;
      }
    }
  }
  
  var my_arr = [2,4,1,0,3,4];
 
  console.log(getHeighest(my_arr));

Upvotes: 0

Eddie
Eddie

Reputation: 26844

Save all index on an array. If only one, send element 0. If multiple return a random element from array.

function getHighest(o) {
  var vals = [];
  for (var i in o) {
    vals.push(o[i]);
  }

  var max = Math.max.apply(null, vals);

  var max2 = []
  for (var i in o) {
    if (o[i] == max) {
      max2.push(i); /* Push the index to temp array */
    }
  }

  if (max2.length == 1) return max2[0]; /* If one element, return first element */
  else return max2[Math.floor(Math.random() * max2.length)]; /* If multiple, select random */
}

console.log(getHighest([1, 2, 3, 4, 2, 3, 4]));

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Here's one approach:

  1. Determine the max:

    var max = Math.max.apply(Math, o);
    
  2. Create an array of only max values:

    var maxes = o.filter(function(val) { return val == max; });
    
  3. Pick randomly from maxes as per this question's answers.

So my goal is to get key with highest value but in case there are more elements with the same highest value choose randomly one of them.

With an array of simple values as shown, it doesn't matter; you could just take the first one, and there's no observable difference between that and any of the others. So presumably your array isn't just simple values — if that's the case, just FWIW, you'll need to find max another way.

Upvotes: 1

Related Questions