1

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

1
  • largestOfFour expects one argument, whereas you pass two. Commented Sep 16, 2015 at 16:50

3 Answers 3

1

Use the map function

array.map(function(array) {
  return Math.max.apply(Math, array)
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that helped out a lot. But how does it know to iterate through both arrays?
1

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;
}

2 Comments

Thanks, that solved one problem. But the iteration is not going through and returning [4,23]
Just made an edit so it returns what you're looking for
1

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(','))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.