I am doing a freecodecamp algorithm scripting problem, and I've gone as far as my understanding will allow. The challenge at hand is to take an array full of 4 sub-arrays of numbers, search through it with javascript, and return a new array with the max value of each sub-array. I've seen their solution and understand it decently, but I've been working on my own solution using nested for loops and a ternary operator. I'll display their solution first, then my faulty solution, where it is saying that the function with arguments is undefined.
Below is the code:
Their Solution:
function largestOfFour(arr) {
var results = [];
for (var n = 0; n < arr.length; n++) {
var largestNumber = arr[n][0];
for (var sb = 1; sb < arr[n].length; sb++) {
if (arr[n][sb] > largestNumber) {
largestNumber = arr[n][sb];
}
}
results[n] = largestNumber;
}
return results;
}
The solution that I am working on (currently doesn't work):
function largestOfFour(arr) {
var maxNum = 0;
var results = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
arr[i][j] > maxNum ? results.push(arr[i][j]) : delete arr[i][j];
}
}
}
For example,
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
should display an array of [5, 27, 39, 1001].
array.map(arr => Math.max(...arr))