The index of the largest float in the array

How can I get the index of the largest element in a float array?

[0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8]

Once I get that index, I then want to get the value of another array at that index.

Let's call the second array:

['a', 'b', 'c', 'd', 'e']

When I ran the following I got 'b'

instead 'c'

.

I iterated over the first array and made a map of floats into strings. Then I got the string in the first element of the first array (float array) sorted.

//aInput in the array of floats.
var emObj={};
for(var i=0; i<aInput.length; i++){
    emObj[aInput[i]]=['a', 'b', 'c', 'd', 'e'][i];
}
return emObj[aInput.sort()[0]];

      

I also tried a method where I iterated over an array of float arrays and stored the largest value in a variable. Then I would do something like this:

return ['a', 'b', 'c', 'd', 'e'][aInput.indexOf(largestFloat)];

      

But none of them worked. I always return the wrong string.

+3


source to share


2 answers


I would suggest using Math.max()

andindexOf()



var maxNum = Math.max.apply(null, aInput);
var index = aInput.indexOf(maxNum);
return ['a', 'b', 'c', 'd', 'e'][index];

      

+5


source


Approach using Array.prototype.reduce()

This allows arbitrary complexity in the reduction logic.

First, set up some data:

  var data = [0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8];
  var reference = ['a', 'b', 'c', 'd', 'e'];

      

Then find the value and index of the maximum value in the array.



  var result = data.reduce(function (previousValue, currentValue, index, array) {
    if(previousValue.value > currentValue) {
      return previousValue;
    } else {
      return {value: currentValue, index: index};
    }
  })
  console.log(reference[result.index]);

      

Alternatively, you can find the reference value directly like this.

var result = data.reduce(function (previousValue, currentValue, index, array) {
  if(previousValue.value1 > currentValue) {
    return previousValue;
  } else {
    return {value1: currentValue, value2: reference[index]};
  }
})
console.log(result);

      

This outputs Object {value1: 0.9573732678543363, value2: "c"}

+1


source







All Articles