how to Find the maximum number in a jagged array given below array of numbers?
const array= [2,4,10,[12,4,[100,99],4],[3,2,99],0];
how to Find the maximum number in a jagged array given below array of numbers?
const array= [2,4,10,[12,4,[100,99],4],[3,2,99],0];
If you know the maximum depth of nesting, then you can flat
the array and find the maximum:
Math.max(...array.flat(depth));
If you don't know the maximum depth, you need to iterate over all the items recursively:
const findMax = item => Math.max(...item.map(row => Array.isArray(row) ? findMax(row) : row));
console.log(findMax([2,4,10,[12,4,[100,99],4],[3,2,99],0]));
You can flat the jagged array using flat
method and after that find max in it. like:
const array = [2,4,10,[12,4,[100,99],4],[3,2,99],0];
const flatArray = array.flat(2);
console.log("Max Value is "+ Math.max(...flatArray));
if you don't know the level of depth
let array = [2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0 ]
let max = 0
function maxNumber(array) {
for (let i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
maxNumber(array[i])
} else {
if (array[i] > max) {
max = array[i]
}
}
}
}
maxNumber(array)
console.log(max)
You could reduce the array and check if the value is an array, then reduce this array or take the value for the wanted function.
const
reduceBy = fn => {
const r = array => array.reduce((a, b) => fn(
Array.isArray(a) ? r(a) : a,
Array.isArray(b) ? r(b) : b
));
return r;
},
array = [2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0],
result = reduceBy(Math.max)(array);
console.log(result);
var arr = [2, 4, 10, [12, 4, [100, 99], 4], [(3, 2, 99)], 0];
function getMax(a) {
return Math.max(...a.map((e) => (Array.isArray(e) ? getMax(e) : e)));
}
console.log(getMax(arr));