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?
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?
Share Improve this question edited Oct 3, 2019 at 11:32 EugenSunic 13.7k15 gold badges66 silver badges95 bronze badges asked Feb 4, 2016 at 13:23 edinvnodeedinvnode 3,5577 gold badges34 silver badges56 bronze badges 4- 3 Simpler: you can do this in one loop. – Salman Arshad Commented Feb 4, 2016 at 13:25
-
1
To start with you can merge 2 loops in 1
for
loop – Nikhil Aggarwal Commented Feb 4, 2016 at 13:25 -
1
You could also trade performance for code size by getting rid of
max
andmin
and writingif (arr[i] > arr[maxIndex])
resp.if (arr[i] < arr[minIndex])
instead. – Erich Kitzmueller 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. – Luuuud Commented Feb 4, 2016 at 13:30
2 Answers
Reset to default 5Well 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
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]))