Search An Array Consisting of Sub-Arrays For the L

2020-02-11 07:59发布

I am working on a coding challenge to take a given array which consists of sub-arrays, search for the largest number in each sub-array, and finally return a new array consisting only of the largest numbers. My thought process was to create variables out of each subarray, write a for-loop comparing each value within the array, then push the largest value to a new array. After writing my first for-loop I tested my code and see that I am getting an unexpected result of the entire first subarray being pushed into my new array. I am looking for the mistake before I write the next three loops. Thank you. Edit: This is for beginner JavaScript coders and the suggestion indicates to use comparison operators in your solution.

function largestOfFour(arr) {
      var one = arr[0];
      var two = arr[1];
      var three = arr[2];
      var four = arr[3];
      var newArr = [];

      for (var i = 0; i < one.length; i++){
        var oneLrg = 0;
        if (one[i] > oneLrg){
          oneLrg = one[i];
          }
        newArr.push(oneLrg);
      }  

  return arr;
}

console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //This test case returns [4,5,1,3] instead of just [5]

9条回答
疯言疯语
2楼-- · 2020-02-11 08:19

You can have a look at this:

function largestOfFour(arr) {
  var newArr=[];
  largestnum=0;
  for(i=0;i<arr.length;i++)
    {
      for(j=0;j<4;j++)
        {
      if(arr[i][j]>largestnum)
        largestnum=arr[i][j];
        }
       newArr.push(largestnum);
      largestnum=0;
    }
return newArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
查看更多
叛逆
3楼-- · 2020-02-11 08:20
function largestOfFour(arr) {
    return arr.map(function(subArray) {
        return subArray.reduce(function(firstArray, secondArray) {
            return firstArray > secondArray ? firstArray : secondArray;
        });
    });
}
largestOfFour([[13, 27, 18, 26],[4, 5, 1, 3],[32, 35, 37, 39],[1000, 1001, 857, 1]
]);
查看更多
看我几分像从前
4楼-- · 2020-02-11 08:22

This post hasn't had any new updates in about 3 months, but I figured I would post my solution to this problem as it looks a bit different than most of the other solutions posted thus far. Figured someone might find it helpful!

I am using quite a few built in method functions( .forEach, .sort, .push, .shift) a quick google search will explain each of these fairly well if you are unsure of how they work. https://developer.mozilla.org is a great resource for these.

function largestOfFour(arr) {
  var newArr = [];                              //set up new empty array
  arr.forEach(function(subArr){                 //iterate through array with .each function
    subArr.sort(function(a, b){                 //use .sort to place largest number of each subarray into index[0]
      return a < b;     
    });
    newArr.push(subArr.shift());                //use .push method to .shift the index[0] number to newArr
  });
  return newArr;                            
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
查看更多
Deceive 欺骗
5楼-- · 2020-02-11 08:24

This function will take two numbers and return their maximum:

var greatest = function(a,b){ return Math.max(a,b); };

This function will take an array of numbers and apply the greatest function to each number in turn (using the .reduce( callbackFunction, initialValue ) method of arrays) to get the maximum value in the array:

var findMaximum = function( arr ){ return arr.reduce( greatest, Number.NEGATIVE_INFINITY ); };

The findMaximum function can be simplified by just calling Math.max() with all the array values (eliminating the need for the greatest function); like this:

var findMaximum = function( arr ){ return Math.max.apply( Math, arr ); };

This function will take an array (of arrays) and call findMaximum on each element of it and return a new array containing those maximums (using the .map( callbackFunction ) method on an array):

var largestOfFour = function( arr ){ return arr.map( findMaximum ); };
查看更多
6楼-- · 2020-02-11 08:26

No doubt that @Austin Hansen and I are leveraging the same learning environment for this challenge: Free Code Camp.

Having just worked through this challenge myself (FCC calls them "Bonfires"), I figured I'd provide solution that heavily dovetails from @Oriol 's excellent ">" solution.

I've included a specific note about the code blocks because to us newbies (at FCC or elsewhere), the absence of such can give us fits for hours : )

function largestOfFour(arr) {
 var finalArray = [];     
 for(i = 0; i < arr.length; i++) { // iterates through each array
   var max = -Infinity;
   for(j = 0; j < arr[i].length; j++) { // iterates through each sub-array 
      if(arr[i][j] > max) { // comparing each successive element within the sub-array to what is currently stored as max
        max = arr[i][j]; //if the ">" comparison is true then max gets updated
      }  
    }
    finalArray.push(max); // ensure this is OUTside of the j for loop. putting it INside the j for loop returns a very long (and wrong) array. try it. 
  }
  console.log(finalArray);
  return finalArray;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");

https://jsbin.com/puweci/edit?js,console

FCC recognizes the follow solution which doesn't NOT leverage Array.push().

function largestOfFour(arr) {
  var results = [];
  for (var i = 0; i < arr.length; i++) {
     var max = -Infinity;
     for (var j = 0; j < arr[i].length; j++) {
        if (arr[i][j] > max) {
        max = arr[i][j];
        }
     }

    results[i] = max;
  }

  return results;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
查看更多
\"骚年 ilove
7楼-- · 2020-02-11 08:28

The problem here is that you're overwriting oneLrg at each loop iteration, and pushing it inside the same loop, so you're comparing each value to 0 and then, as one[i] is bigger, saving it.

Try this:

var oneLrg = 0;
for (var i = 0; i < one.length; i++){
    if (one[i] > oneLrg){
        oneLrg = one[i];
    }
}
newArr.push(oneLrg);  
查看更多
登录 后发表回答