itzmurd4
itzmurd4

Reputation: 663

Finding Largest Values in Array of Arrays

I am trying to return arr with the largest element in each array, however I am receiving an error message. Thanks.

function largestOfFour(arr) {
  for (var i = 0; i<arr.length; i++) {
    return Math.max.apply(Math, arr[i]);
    }
}

largestOfFour([1,2,4],[23,22,0])

TypeError: second argument to Function.prototype.apply must be an array

Upvotes: 1

Views: 50

Answers (3)

Jon Carter
Jon Carter

Reputation: 3406

You're not passing your function an array of arrays -- you're passing it TWO arrays. :)

Try this:

largestOfFour([[1,2,4],[23,22,0]])
              ^                 ^

Additionally, largestOfFour, as defined, returns the max the first time it runs -- in effect, returning the max value of the first array in the array of arrays.

To do it that way, you could save the max each time, then return the max of that.

Or take advantage of join()'s apparent flattening of nested arrays and do this:

Math.max.apply(null, a.join().split(','))

Upvotes: 1

tcigrand
tcigrand

Reputation: 2397

Currently, you're sending two params to largestOfFour, but you should just send one, with an array at each index.

largestOfFour([[1,2,4],[23,22,0]])

In order to get the return result you're looking for.

function largestOfFour(arr) {
  var returnArray = []
  for (var i = 0; i<arr.length; i++) {
    returnArray.push(Math.max.apply(Math, arr[i]));
    }

  return returnArray;
}

Upvotes: 1

Richard Hamilton
Richard Hamilton

Reputation: 26434

Use the map function

array.map(function(array) {
  return Math.max.apply(Math, array)
})

Upvotes: 1

Related Questions