1. 程式人生 > >取二維數組最大值

取二維數組最大值

www apply http cti length mat 需要 -i turn

//取二維數組最大值


var test=[[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]];

//1. junior
function getMaxOne(arr){
var tmp=[];
for(var i=0;i<arr.length;i++){
tmp[i]=0;
for(var j=0;j<arr[i].length;j++){

if(tmp[i]<arr[i][j]){
tmp[i]=arr[i][j];
}
}

}
return tmp;
}
var rel=getMaxOne(test);
//console.log(rel)



//2. middle
function fungetMax(arr){
return arr.map(function(currentvalue,index,array){
return currentvalue.reduce(function(standard,current){
return standard>current?standard:current;
});
})


}
var rem=fungetMax(test);
//console.log(rem)



//3. senior
function max(arr){
return arr.map(Function.apply.bind(Math.max,null));
}




//基於senior
function mySenior(arr){
return arr.map(function(currentValue,index,arr){
return Math.max.apply(null,currentValue)//apply傳入null表示不需要上下文
})

}
var me=mySenior(test)
//console.log(‘me=‘+me)




//4. smart 二維數組的最大值
function smart(arr){
//將二維乃至多維數組合並
var newArr=arr.join(‘,‘).split(‘,‘);
return Math.max.apply(null,newArr);
}
var smart=smart(test)
//console.log(smart)

<html>

參考自<a href=http://www.w3cplus.com/javascript/algorithm-return-largest-numbers-in-arrays.html>大漠</a>

</html>

取二維數組最大值