1

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?

Prograbit
  • 13
  • 2

4 Answers4

4

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)
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32
0

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>
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Hyperella
  • 60
  • 4
0

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.

0

sort and get the first

var arr = [{
  x: 500,
  y: 400
}, {
  x: 80,
  y: 400
}, {
  x: 900,
  y: 400
}];
arr.sort((a, b) => a.x < b.x ? -1 : (a.x > b.x ? 1 : 0));
console.log(arr[0]);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Soshiv Upreti
  • 101
  • 1
  • 6