3

I've made this solution.

var arr=[4,10,24,3,2,2,19];

var max = arr[0];
var maxIndex = 0;
var min = arr[0];
var minIndex = 0;

for (var i = 1; i < arr.length; i++) {
  if (arr[i] > max) {
    maxIndex = i;
    max = arr[i];
  }
}
for (var i = 1; i < arr.length; i++) {
  if (arr[i] < min) {
    minIndex = i;
    min = arr[i];
  }
}

alert(maxIndex);
alert(minIndex);

Is there a simpler way to do the task above?

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
edinvnode
  • 3,497
  • 7
  • 30
  • 53

2 Answers2

5

Well with reduce you can use the index and array arguments:

var arr=[4,10,24,3,2,2,19];

var maxIndex = arr.reduce(function(highestIndex, element, index, array){
    return element > array[highestIndex] ? index : highestIndex;
}, 0);

For both min and max:

var limits = arr.reduce(function(limits, element, index, array){
    limits.max = element > array[limits.max] ? index : limits.max;
    limits.min = element < array[limits.min] ? index : limits.min;
    return limits;
}, { max : 0, min : 0 });
//limits.max === Highest value index,
//limits.min === Lowest value index
MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • 1
    Still needs two calls to `reduce`, though, if you do it that way. Can be done with a single call, but then you're not really `reduce`ing anymore, it's just a `forEach`. – T.J. Crowder Feb 04 '16 at 13:28
  • @T.J.Crowder, why does it need two `reduce` calls? – MinusFour Feb 04 '16 at 13:34
  • One for the min, one for the max, the way you've written it. – T.J. Crowder Feb 04 '16 at 13:36
  • Ah, right I didn't even see the `min` part, it's possible to do with one reduce (i think). – MinusFour Feb 04 '16 at 13:37
  • It is, but as I said, at that point you're not really `reduce`ing anymore. – T.J. Crowder Feb 04 '16 at 13:39
  • @T.J.Crowder, aren't you introducing a list of numbers and getting a single value instead (although granted, that value is a collection)? – MinusFour Feb 04 '16 at 13:43
  • If the accumulator never changes (and it doesn't, in your update; that's just the same object reference being passed into and out of the callback each time), you're not really `reduce`ing. It's just a `forEach` with the accumulator passed around and ultimately out of the function rather than simply closing over it. – T.J. Crowder Feb 04 '16 at 13:47
1

Here is a standard way of doing it (without functional programming).

You find the min and max value, when found, just set the current indexes of the loop to the minIndex/maxIndex variables.

 function findIndexOfMinMax(arr) {
   let minIndex = 0;
   let maxIndex = 1;
   let min = arr[0];
   let max = arr[1];

   for (let i = 0; i < arr.length; i++) {
     if (arr[i] < min) {
       min = arr[i];
       minIndex = i;
     }
     if (arr[i] > max) {
       max = arr[i]
       maxIndex = i;
     }
   }
   return {
     minIndex,
     maxIndex
   };
 }

 console.log(findIndexOfMinMax([9, 4, -1, -1, 7, 8, 0, 11]))
EugenSunic
  • 13,162
  • 13
  • 64
  • 86