I'm going through freeCodeCamp and am having trouble with their "Return Largest Numbers in Arrays" problem. The issue seems to be with my code for finding every fourth element in the second "for" loop. It looks like it's including the commas from the array "decArray". Any ideas on how to fix this or reorient my thinking process? I appreciate it!
The Instructions:
- Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
- Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].
- largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
- largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001].
- largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].
Here's My Code:
function largestOfFour(arr) {
var decArray = []; // initialize variable to sort each subarray in descending order
var finalArray = []; // initialize variable for final array
// sort array values in descending numerical order instead of by alphabetical order
function sortNumber(a,b) {
return a - b;
}
// loop through initial array to sort each subarray in descending order
for (var i = 0; i < arr.length; i++) {
decArray += arr[i].sort(sortNumber).reverse() + ",";
}
// loop through decArray to find every fourth element
for (var j = 0; j < decArray.length; j += 4) {
finalArray.push(decArray[j]);
}
// return the final array
return finalArray;
}
// test array
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
... + ","supposed to accomplish?function largestOfFour (arr) { return arr.map(a => Math.max(...a)); }