2016-03-02 78 views
2

我想要一個返回數組最大值的函數。 我知道這個問題被問了很多次,但是在一個數組中,我們有多於一個的最高值呢? 讓我們假設,我們的陣列看起來像這樣:數組中最大值的返回索引

var arr = [1,10,2,10]; 

功能:

arr.indexOf(Math.max.apply(Math, arr)); 

將返回唯一指標1,但我想獲得1和3

什麼是最短的並且是最有效的方式。

+0

你將不得不寫你自己的方法我認爲 –

回答

4
const largest = Math.max(...arr); 
arr.reduce((indexes, n, index) => { 
    return indexes.concat(n === largest ? [index] : []); 
}, []); 

或者,如果ES5是你的那杯茶:

var largest = Math.max.apply(Math, arr); 
arr.reduce(function(indexes, n, index) { 
    return indexes.concat(n === largest ? [index] : []); 
}, []); 

或者,如果通用功能是你的事:

function findAllIndexes(arr, val) { 
    return arr.reduce((indexes, element, index) => { 
    if(element === val) { 
     return indexes.concat([element]); 
    } else { 
     return indexes; 
    } 
    }, []); 
} 

findAllIndexes(arr, Math.max(..arr)); 
1

這會工作:

var arr = [1,10,2,10], 
    indices = [], 
    highest = Math.max.apply(Math, arr); 
arr.forEach(function(val, index){ 
    if (val === highest) indices.push(index); 
}); 
console.log(indices.join(',')); 
1

您可以使用此。

var arr = [1,10,2,10]; 
var ind = []; 
var highValue = Math.max.apply(Math, arr); 
arr.map(function(x, i) { 
    if (x == highValue) { 
    ind.push(i) 
    } 
}); 
console.log(ind);//output is [1,3] 
+0

T他是O(N^2),先計算最大值,然後遍歷數組,即O(N)。 –

+0

對不起,我忘記了 – htoniv

0

var highestIndexes = []; 
 
$.each(arr,function(index,item){ 
 
    item== Math.max.apply(Math, arr) ? highestIndexes.push(index) : $.noop(); 
 
}); 
 
console.log(highestIndexes);

試試這個

2

「手工」 的方式:

var getIndicesOfHighest = function(arrIn) { 
     var indices = []; 
     var highest = arrIn[0]; 
     for (var el=1; el<arrIn.length; el++) { 
      if(arrIn[el] > highest) { 
       highest = arrIn[el]; 
       indices = []; 
       indices.push(el); 
      } else if (arrIn[el] == highest) { 
       indices.push(el); 
      } 
     } 
     return indices; 
    } 
0

只是爲了完整性,用Array#reduce()

var arr = [1, 10, 2, 10], 
 
    max = arr.reduce(function (r, a, i, aa) { 
 
     if (!i || a > aa[r[0]]) { 
 
      return [i]; 
 
     } 
 
     if (a === aa[r[0]]) { 
 
      r.push(i); 
 
     } 
 
     return r; 
 
    }, []); 
 

 
document.write('<pre>' + JSON.stringify(max, 0, 4) + '</pre>');

0

的建議使用下劃線/ lodash和_.reduce你可以寫一個方法來查找所有基於whateve的索引[R條件你在傳遞

我愛:

function findAllIndexes(_arr, condition) { 
    return _.reduce(_arr, function(arr, o, index) { 
    if(condition(o, _arr)) arr.push(index); 
    return arr; 
    }, []); 
} 

console.log(findAllIndexes(nums, function(o, arr){ 
    return o === Math.max.apply(Math, arr); 
})); 

同樣的方法可以與對象litetals的陣列可以使用任何條件,你給它

var users = [ 
    { 'user': 'barney', 'active': true }, 
    { 'user': 'barney', 'active': false }, 
    { 'user': 'bob', 'active': false } 
]; 

console.log(findAllIndexes(nums, function(o, arr){ 
    return o.user == 'barney' && o.active == false;  
})); 

http://jsbin.com/jadesayicu/edit?html,js,console,output