function largestOfFour(arr) {
var newArray = [];
for(var i =0; i <=arr.length-1; i++){
console.log(arr[i]);
newArray[i] = Math.max(arr[i]);
Using lodash
var x = ([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
_.flatten(x).max();
You are passing an array to Math.max
and expect it to return the maximum in that array.
However, Math.max
returns the maximum among its arguments. So use
var newArray = [];
for(var i =0; i < arr.length; ++i)
newArray[i] = Math.max.apply(void 0, arr[i]);
In ES6, you can use arrow functions and the spread operator to simplify:
arr.map(a => Math.max(...a));
It won't work like that. Math.max
expect separate numbers. You can get desired output using apply
function largestOfFour(arr) {
return arr.map(function(subArr){
return Math.max.apply(Math, subArr);
});
}
If you want the ultimate max do this.
var original = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
Math.max.apply(null, original.map(function(arr) { return Math.max.apply(null, arr); }));
or if you want a the max of each array just do
original.map(function(arr) { return Math.max.apply(null, arr); });
Edited: In order to add values to the array, I'd suggest using the push methodn. As in: NewArray.push(Math.max(...sub[i])); or newarray.push(math.max.apply(null, sub[i]). An alternative is alocating, when declarating the array, the size it will take: Var newArray = new Array(arr.length); There's this new spread operator (...) in javascript !