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?

4
  • 3
    Simpler: you can do this in one loop. Commented Feb 4, 2016 at 13:25
  • 1
    To start with you can merge 2 loops in 1 for loop Commented Feb 4, 2016 at 13:25
  • 1
    You could also trade performance for code size by getting rid of max and min and writing if (arr[i] > arr[maxIndex]) resp. if (arr[i] < arr[minIndex]) instead. Commented Feb 4, 2016 at 13:26
  • If you don't care about the order of your original Array, you can first sort it and get the first and last element. Commented Feb 4, 2016 at 13:30

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

7 Comments

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 reduceing anymore, it's just a forEach.
@T.J.Crowder, why does it need two reduce calls?
One for the min, one for the max, the way you've written it.
Ah, right I didn't even see the min part, it's possible to do with one reduce (i think).
It is, but as I said, at that point you're not really reduceing anymore.
|
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]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.