Hello all I am working on this challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays
and I have been able to get the code to return an array, but it is filled with the two highest numbers of each sub-array rather than just the single highest number. my code follows:
function largestOfFour(arr) {
let sorted = [];
for (let i = 0; i < arr.length; i++) {
let arrInner = arr[i];
for (let j = 0; j < arrInner.length; j++) {
sorted.push(arrInner.sort().pop());
}
} return sorted;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
so I am getting [5,4,27,26,39,37,857,1001] rather than [5, 27, 39, 1001].
Any help is greatly appreciated!
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.
Note: Backticks are not single quotes.
How are you testing to make sure that the number you are adding to the array is the largest?
- If it were not for the fact that you changed the length of the innerArray (by pop) you would just get the full array back in sorted order.
Removing the inner loop:
function largestOfFour(arr) {
let sorted = [];
for (let i = 0; i < arr.length; i++) {
let arrInner = arr[i];
sorted.push(arrInner.sort().pop());
}
return sorted;
}
Returns: [5, 27, 39, 857]
- Sorting the last array is not giving you what you want.
[1000, 1001, 857, 1].sort().pop()
Returns: 857
Hey I figured it out, thanks for cluing me in on that unnecessary inner loop! That really got the ball rolling. I ended up running a function inside of sort() as follows:
sorted.push(arrInner.sort(function( a, b) {return a - b}).pop());
This “sorted” (pun totally intended) the rest of the code out and now it is working. Thanks all for your input!