Find the largest number in each of the sub-array and then make an array of those largest numbers.[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1
I know the question here is to find a bug in the existing code, in case if you may want to optimise the code
The original idea is of @thefourtheye. I'm just explaining this here.
No need of nested loops, you can achieve this in single line.
var arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var result = arr.map(Math.max.apply.bind(Math.max, null));
document.write(result);
console.log(result);
How this works?
The array.map function is iterating over each of the elements from array on which it is called.
The function passed to the map here is apply with its this context bound to the Math.max and first argument bound to null.
Math.max.apply.bind(Math.max, null) this basically calls the Math.max function on array as
Math.max.apply(null, array);
Update:
With ES6, arrow function and spread operator, this can be made even smaller
arr.map(e => Math.max(...e))
var arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var result = arr.map(e => Math.max(...e));
document.write(result);
console.log(result);