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)
You can use lodash
var array = [{
x: 500,
y: 400
}, {
x: 80,
y: 400
}, {
x: 900,
y: 400
}];
console.log(_.minBy(array, 'x'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
let min = Infinity
for (var i=0; i<array.length; i++){
if (array[i].x<min) min = array[i].x
}
Here min is your answer. There might be easier way to do this, but his gets the job done.