main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 
//@riteshprk's version from FCC--http://forum.freecodecamp.com/t/return-largest-numbers-in-arrays-help/40874

function largestOfFour(arr) {
var myArr = [];
//var maxValue = 0;

  for (var i=0; i<arr.length; i++){
  var maxValue = 0;
    for ( var j=0; j<arr[i].length; j++){
      if (arr[i][j]>maxValue){
        maxValue = arr[i][j];
        
      } 
    } 
    myArr.push(maxValue); //I moved this line: it needs to be after the "[i] for loop" and before the [j]
  } 
  return myArr; //I moved this: it needs to be inside the function but outside both for loops
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1], [1,2]]);


/*
// SIMPLE VERSION: works in FCC 
function largestOfFour(array) {
  var newArray = []; 
  var largest = 0; 
  
  for(var i = 0; i<array.length; i++) {
    for(var j = 0; j<array[i].length; j++) {
    var subItem = array[i][j];

      if (subItem > largest) { 
        largest = subItem;
      } 
    } 
    newArray.push(largest); 
  } 
  return newArray; 
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1], [1,2]]);
*/

/*
//EXPANDED VERSION --comments and console.logging to track the process

function largestOfFour(array) {
// declare variables --best to do inside function to avoid accidental globals 
  var newArray = []; //must be declared before first for loop
  var largest = 0; //declare here for cleaner code; works to declared inside "[i] for loop"; 
  
  console.log("array length = "+array.length);
  for(i = 0; i<array.length; i++) {
    for(j = 0; j<array[i].length; j++) {
      var subItem = array[i][j];  //declared var to make for clearer self-documenting code
      console.log("subItem: "+subItem);
    
      if (subItem > largest) {  //could have used "if(array[i)[j] > largest) {}" etc.
        largest = subItem;
      }  
    } 
    console.log("largest in [" + array[1] + "] = " + largest);
    newArray.push(largest); 
  } 
  return newArray; //Couldn't get this to work for the longest time: Then I put the return statement in the right place--inside the function/after both for loops
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1], [1,2]]);

*/
Native Browser JavaScript