0

I currently have data stored for a line chart with an array of another array of tuples, so for example [[[1,2],[3,4]], [[5,6],[7,8]]]. What's the best way to get the maximum Y value across all lines from this structure?

I could create a helper function to get the maximum Y from an array, and then create a helper function to call the first helper function while looping through every line's data. Is there a much simpler way that I'm missing here? Thanks in advance

1
  • What is the expected output? Please include your code attempt in the question. Commented Aug 1, 2021 at 3:39

1 Answer 1

1

Here's a straightforward take on this using Array.map:

const tuples = [
  [1, 2],
  [3, 4],
  [2, 3],
]

const max = Math.max(...tuples.map((tuple) => Math.max(...tuple)))

console.log(max)  // 4

This is essentially what you described in your question; the "helper function" is the inlined arrow function (tuple) => Math.max(...tuple)), which finds the maximum value in each tuple when mapped over tuples.

Unfortunately, Math.max doesn't take arrays directly, so you need to unpack the array in the call using the spread operator ....

Note that the Array.map usage is equivalent to the for loops you suggest in your question, just more compact and expressive to type out.

Whether you agree that this is "simpler" is, I suppose, up to you...

Sign up to request clarification or add additional context in comments.

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.