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.
CodePudding user response:
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')
CodePudding user response:
You can use Array.reduce
:
var list = [{
x: 200,
y: 400
}, {
x: 120,
y: 400
}, {
x: 170,
y: 400
}];
const res = list.reduce((a,b) => a = b.x > a.x ? b : a, list[0])
console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
To find the object with the greatest value of x, use the Array#filter()
method to only return object(s) that have the max value of x as determined by Math.max( ...arr )
. The 0
index ([0]
) ensures an object is returned; if there are more than two objects, the first will be returned:
const oMaxX = list.filter(obj => obj.x === Math.max( ...list.map(a => a.x) ) )[0];
DEMO
const list = [
{ x: 200, y: 400 },
{ x: 120, y: 400 },
{ x: 170, y: 400 }
];
const oMaxX = list.filter(obj => obj.x === Math.max( ...list.map(a => a.x) ) )[0];
console.log( oMaxX );
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>