javascript - Get array index by Max value? -
javascript - Get array index by Max value? -
this question has reply here:
javascript: min & max array values? 32 answers return index of greatest value in array 5 answersi found solutions max value of indexes, how can max value when have array this:
myarray = []; myarray[1] = 10; myarray[2] = 99; alert(math.max(myarray));
i index of max value. in case index 2 of value 99.
the result nan.alert(math.max(myarray));
1. if want first instance:
var arraymaxindex = function(array) { homecoming array.indexof(math.max.apply(null, array)); }; console.log(arraymaxindex([1,2,7,2])); //outputs 2
2. if want occurrences of max:
function getallindexes(arr, val) { var indexes = [], = -1; while ((i = arr.indexof(val, i+1)) != -1){ indexes.push(i); } homecoming indexes; } var arrayallmaxindexes = function(array){ homecoming getallindexes(array, math.max.apply(null, array)); } console.log(arrayallmaxindexes([1,2,7,2,7])); // outputs [2,4]
javascript arrays
Comments
Post a Comment