Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Greatest Value in an object

I am making a game with obstacles at different x and y coordinates and I am put all the obstacles into a list like so:

var list = [{x:200, y:400},{x:120, y:400},{x:170, y:400}];

I am trying to find the object with the greatest x value.
Is there some kind of max() function for objects like these? So I can find the max object?
Max X: 200
Also please do forgive my if my questions are sloppy and have some errors, I am still a child at age 12 and do not find these errors often.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Firstly, what you showed is not a proper object in JavaScript. I guess the proper list you want to present is like below?

var list = [
  { x: 200, y: 400 },
  { x: 120, y: 400 },
  { x: 170, y: 400 }
]

Then, if you want to get the max value, try this:

function getMaxValue(list, key) {
    const keyArray = list.map(l => l[key])
    return Math.max(keyArray)
}

By using above function, if you want to find the max x, try getMaxValue(list, 'x'). If you want to find the max y, try getMaxValue(list, 'y')

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading