Locate the index of the highest and lowest value of an array

Asked

Viewed 188 times

2

How do I locate the position of the largest and smallest element in a Javascript array?

With the reduce I was able to locate the largest and smallest element, but I need to get the position (index) also from them inside the array.

Greater number:

var array = ["885.9", "984.9", "444.9", "528.9", "528.9"];  
var maior_numero = array.map(Number).reduce(function(numero1, numero2) {  
  return Math.max(numero1, numero2);  
});  
        
console.log(maior_numero ); 

Fewest:

var array = ["88", "999", "12", "123", "230"];  
var menor_numero = array.map(Number).reduce(function(numero1, numero2) {  
  return Math.min(numero1, numero2);  
});  
        
console.log(menor_numero ); 
  • I think the reduce then it’s kind of unnecessary. You could have done something like Math.max.apply(null, ["885.9", "984.9", "444.9", "528.9", "528.9"])

  • 1

    Thanks Wallace for the feedback, so this code you helped me with is taking the value of the element. Besides the precise pick value in which position it is in the array, it could help me?

2 answers

3

You can use a for simple, storing the indices of the highest and lowest number and modifying them if necessary.

This way, you only need to scan the array once.

Something like that:

function indexes(arr) {
  if (!arr.length) {
    return null;
  }
  
  let max = 0;
  let min = 0;
  
  for (let i = 0; i < arr.length; i++) {
    const current = arr[i];
    
    if (current > arr[max]) {
      max = i;
    }
    
    if (current < arr[min]) {
      min = i;
    }
  }
  
  return { max, min };
}

console.log(indexes([3, 5, 6, 2, 1, 4])); // { max: 2, min: 4 }
console.log(indexes([1, 2])); // { max: 1, min: 0 }
console.log(indexes([])); // null

It doesn’t make much sense for you to pass one directly array of strings for Math.max or something of the kind, since it is the type of incorrect data. It is pertinent to convert the elements before try to compare them, or you may end up encountering some bizarre situations, since the comparison between strings is different from the comparison between numbers.

We can modify the above code to handle arrays of strings:

function indexes(arr) {
  if (!arr.length) {
    return null;
  }
  
  let max = 0;
  let min = 0;
  
  for (let i = 0; i < arr.length; i++) {
    const current = parseFloat(arr[i]);
    
    if (current > parseFloat(arr[max])) {
      max = i;
    }
    
    if (current < parseFloat(arr[min])) {
      min = i;
    }
  }
  
  return { max, min };
}

console.log(indexes(["885.9", "984.9", "444.9", "528.9", "528.9"])); // { max: 1, min: 2 }

Javascript has some native mechanisms of automatic coercion of type, but they do not always make sense. To avoid problems (which will actually occur if you don’t treat the data correctly - see an example here), always prefer to perform conversions explicit. :-)

  • 1

    Thank you very much Luiz Felipe, helped me a lot! Hug!

2

To get the higher or lower value, you can simply do so:

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var maior = Math.max.apply(null, arr) 

Now to get the position just use indexOf

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"].map(Number);
var maior = Math.max.apply(null, arr) 

console.log(maior);

console.log(arr.indexOf(maior));

Note that in the case of indexOf, I needed to call map(Number), that’s because indexOf considers the type of the variable. How Math.max returns Number, indexOf would return -1, for not finding the value of the same type and value (since its array is a list of strings).

So you don’t have to convert everything with the map, you could also use a toString() on the return of Math.max or Math.min.

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var maior = Math.max.apply(null, arr) 

console.log(maior);

console.log(arr.indexOf(maior.toString()));

Simplifying code for understanding:

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];

var maior = Math.max.apply(null, arr) 
var posicao_maior = arr.indexOf(maior.toString()));

var menor = Math.min.apply(null, arr) 
var posicao_menor = arr.indexOf(menor.toString()));

Note: To find the value of Math.min, the rule is the same as the code I made above with Math.max, just replace.

  • 1

    Thanks a lot Wallace, helped me a lot too! Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.