PeregrineofPassage
PeregrineofPassage

Reputation: 13

Using sort to return an array of largest numbers from subarrays

I'm a beginning coder who has been learning through FCC. I'm currently trying to solve an algorithm challenge in which I must return an array consisting of the largest number from each subarray. Explanations of what I'm missing or doing incorrectly are greatly appreciate, as it is currently only returning the zero index of the first array.

my code so far:

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

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

Upvotes: 0

Views: 55

Answers (3)

akuiper
akuiper

Reputation: 215127

You could use map function on the array, and for each sub array take the maximum value:

arr.map(x => Math.max(...x))
# [ 5, 27, 39, 1001 ]

Or:

arr.map(x => Math.max.apply(null, x))
# [ 5, 27, 39, 1001 ]

Upvotes: 1

brk
brk

Reputation: 50346

The function is not executing for the entire length of the array as it encounters return statement after first iteration.In this case the objective is to find largest from each of the sub array, so the function to find largest has to be triggered on each and every subarray

 // find largest in each subarray.the largest will be at 0 index
function largestOfFour(arr) {
  return arr.sort(function(a, b) {
    return b - a
  })[0];


}
var array = [
  [4, 5, 1, 3],
  [13, 27, 18, 26],
  [32, 35, 37, 39],
  [1000, 1001, 857, 1]
]

// looping through the array
array.forEach(function(item) {
  //item will be each subarray
  console.log(largestOfFour(item))

})

Upvotes: -1

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

You are returning from the very first iteration of the loop. (return terminates the whole function thus the loop is useless). You need to return after the loop finishes, thus you need a new way of storing the results (another array).

Since you are looking for the maximum number, Math.max will be better than sort:

function largestOfFour(arr) {
   var i = 0;
   var results = [];                              // the results array (the array that will contain the maximum numbers)
   for (i = 0; i < arr.length; i++) {
       var max = Math.max.apply(null, arr[i]);    // get the maximum number for the current array (if you want to use sort, it won't be a problem but Math.max is better)
       results.push(max);                         // add this maxumum number to the results array
   }
   return results;                                // when the loop finishes (we got all the maximums), then return
}

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

Upvotes: 1

Related Questions