Finding an array of subarrays for the largest number and returning to a new array

I am working on a coding problem to take a given array that consists of sub-arrays, find the largest number in each sub-array, and finally return a new array consisting of only the largest numbers. My thought process was to create variables from each subarray, write a for-loop comparing each value in the array, and then push the largest value onto the new array. After writing my first loop, I checked my code and saw that I was getting an unexpected result for the entire first subarray that fits into my new array. I am looking for a bug before writing the next three loops. Thank. Edit: This is for beginner JavaScript codes and this sentence points to the use of 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]

      

+3


source to share


9 replies


Usage >

:

var newArr = [];
for(var i=0; i<arr.length; ++i) {           // Iterate array
  var maximum = -Infinity;                  // Initial maximum
  for(var j=0; j<arr[i].length; ++j)        // Iterate subarrays
    if(arr[i][j] > maximum)                 // Compare
      maximum = arr[i][j];                  // Update maximum
  newArr.push(maximum);                     // Store the real maximum
}

      

Usage Math.max

:

var newArr = [];
for(var i=0; i<arr.length; ++i) {           // Iterate array
  var maximum = -Infinity;                  // Initial maximum
  for(var j=0; j<arr[i].length; ++j)        // Iterate subarrays
    maximum = Math.max(maximum, arr[i][j]); // Update maximum
  newArr.push(maximum);                     // Store the real maximum
}

      

Adding apply

:

var newArr = [];
for(var i=0; i<arr.length; ++i)     // Iterate array
  newArr.push(                      // Store ...
    Math.max.apply(Math, arr[i])    // ... the maximum of the subarray
  );

      



Adding ECMAScript 5 map ,

var newArr = arr.map(function(subarray) {
  return Math.max.apply(Math, subarray);
});

      

Adding ECMAScript 5 bind ,

var newArr = arr.map(Function.apply.bind(Math.max, Math));

      

Or adding ECMAScript 6 arrow function and spread operator ,

var newArr = arr.map(subarray => Math.max(...subarray));

      

+12


source


The problem is that you are overwriting oneLrg

on each iteration of the loop and pushing it inside one loop, so you compare each value to 0, and then, when one[i]

greater, store it.

Try the following:



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

      

+1


source


No doubt @Austin Hansen and I are using the same learning environment for this task: Free Code Camp.

After working through the challenge itself (the FCC calls them "Bonfires"), I decided I would put up a solution that strongly aligns with the excellent ">" solution from @Oriol.

I've included a specific note on code blocks because for us newbies (at the FCC or elsewhere), the lack of them might give us a chance 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

The FCC recognizes the following solution, which does not use 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]], "");

      

+1


source


This function will take two numbers and return the maximum of them:

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

      

This function will take an array of numbers and apply the function greatest

to each number in turn (using the .reduce( callbackFunction, initialValue )

arrays method ) to get the maximum value in the array:

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

      

A function findMaximum

can be simplified by simply calling it Math.max()

with all the values ​​in the array (eliminating the need for a function greatest

); eg:

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

      

This function will take an array (of arrays) and call findMaximum

for each of its elements and return a new array containing these maxima (using .map( callbackFunction )

in the array):

var largestOfFour = function( arr ){ return arr.map( findMaximum ); };

      

0


source


This post hasn't had any new updates in about 3 months, but I figured I would post my solution for this issue as it differs slightly from most of the other solutions posted so far. Realized that someone might find it useful!

I use quite a few built-in method functions (.forEach, .sort, .push, .shift), a quick google search will explain each one well enough if you don't know how they work. https://developer.mozilla.org is a great resource for them.

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]]);

      

0


source


You can 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]]);

      

0


source


@orion - your answer didn't work for me. If the press is inside an if statement, then pressing numbers that were not supposed to be in the array. As a result, the former would push [4,5] and hurt the job. So I moved push from the for statement and reset lgstNumber to 0 also after that so that it doesn't use it for the next sub-matrix. This worked for me ...

function largestOfFour(arr) {
  // You can do this!
  var newArr = [];
  var lgstNumber = -  Infinity;
  for(var i = 0; i < arr.length; i++){
    for(var j = 0; j < arr[i].length; j++){
      if(lgstNumber < arr[i][j]){
        lgstNumber = arr[i][j];
      }
    }
    newArr.push(lgstNumber);
    lgstNumber = 0;
  }
  return newArr;
}

      

0


source


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]
]);

      

0


source


more efficient.

function largestOfFour(arr) {


  for(var x=0;x<arr.length;x++)
    {
       for(var y=0;y<arr[x].length;y++)
        {
           arr[x]=arr[x].sort(function(a,b)
                   {
         return b-a;
       });

     }
}
  var array=[];
  for(var a=0;a<arr.length;a++)
{
  for(var b=0;b<arr[a].length;b++)
    {
      if(b==0)
        {
          array[a]=arr[a][b];
        }
    }


}
  return array;

}

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

      

0


source







All Articles