I am making a game with obstacles currently and I want to find the object with the lowest X value. Here is an example of an array.
var array = [{x:500, y:400}, {x:80, y:400}, {x:900, y:400}];
I want to be able to determine what is the lowest X in this group(80) and return it to me. Is there any way to do this?
You don't need to sort the array or use an external library. You can use Array.prototype.reduce
to find the object with minimum x
in linear time:
const array = [{x:500, y:400}, {x:80, y:400}, {x:900, y:400}];
const minX = array.reduce((acc, curr) => curr.x < acc.x ? curr : acc, array[0] || undefined);
console.log(minX)