How to find the maximum of an irregular two-dimensional array
given an array, for example:
var arr = [
["1","15","56"],
["1","15","56"],
["3","-","56"],
["1","78","-"],
["1","-","56"],
]
is there any elegant way to find the maximum value of the irregular two-dimensional array shown in the figure?
es6 is simple, if the two-dimensional array is pure numbers, then
const max = Math.max(...[].concat(...arr));
console.log(max)
but I see that your array contains characters like -
, so you have to go through Filter
first.
const max = Math.max(...[].concat(...arr.map(_arr => _arr.map(v => isNaN(v) ? 0 : v))));
console.log(max)
es5 just cycle through it. It's ugly no matter how you write it.
var max = 0;
arr.forEach(function (_arr) {
_arr.forEach(function (v) {
if (!isNaN(v) && v > max) max = v
})
});
console.log(max)
var arr = [
['1','15','56'],
['1','15','56'],
['3','-','56'],
['1','78','-'],
['1','-','56'],
];
function dparseInt(i){
var j = parseInt(i);
if( isNaN(j) ) return 0;
return j;
var arr = [
['1','15','56'],
['1','15','56'],
['3','-','56'],
['1','78','-'],
['1','-','56'],
];
function dparseInt(i){
var j = parseInt(i);
if( isNaN(j) ) return 0;
return j;
}
//
var arr1 = arr.map(item=>{
return item.map(i => dparseInt(i));
});
console.log(arr1);
//Math.max
var result = Math.max(...arr1.map(v=>Math.max(...v)))
console.log(result)
Math.max.apply(null, arr.map(function(el) {
return Math.max.apply(null, el.filter(function(item) {return +item}))
}))
try the subject