There is a dynamic array of objects with coordinates, you need to get an object with the maximum value of x:

var mass = [{ x: 34 }, { x: 12 }, { x: 2 }, { x: 348 }, { x: 15 }]; var maxObj = Math.max(mass[i].x); 
  • Create the variable "maximum", iterate the array and rewrite the variable if the value in the current element being iterated is greater than in the variable. - etki

1 answer 1

Array.prototype.reduce ()

 var maxObj=mass.reduce(function(prev,cur) { return cur.x>prev.x?cur:prev; },{x:-Infinity}); 

in ES6 it will be a bit shorter (and IMHO is not clearer):

 let maxObj=mass.reduce((prev,cur) => cur.x>prev.x?cur:prev,{x:-Infinity}); 

Update

var is not going anywhere, and this is not coffee. let is different from var like this:

 var i=1;for (var i=0;i<10;i++){};console.log(i); //10 var i=1;for (let i=0;i<10;i++){};console.log(i); //1 
  • Cool, coffee make nativym. But why replace the usual for almost all var languages ​​with let ... - vas
  • Awesome! Exactly what you need. Thank you) - panfilov
  • one
    @eicto, me too. The file on the disk will take exactly 1 block (with the file data in it (also 0) - 1 byte). Only here it is not very easy to distinguish the real 0 in the file from the empty block generated when reading. Therefore, the comparison of zero byte with undefined data (apparently, there is such a concept in js) looks a bit strange. - @eicto, my comments are over, so I’m just writing here. I (as you already understood) read 2 of your extreme comments about arrays in js, thanks. Maybe someday I'll learn js. - avp
  • one
    Well, the values ​​in the array are references to data, in the file system undefined it is difficult to describe (programs will not expect this for sure), but in js it is easy. Ie, I think, there it is - there is no link in the cell (rather, there is even no entry in the dictionary), which means - undefined. Why in js it is called Array, not very important, because There is no other similar type in js. > var a = []; a [10000] = 1; > Object.keys (a) Array ["10000"] Ie Array itself is just an object with numeric keys and a known length. - zb '
  • one
    Here's another example:> var b = {1000: 1,1001: 2, length: 1002}; var c = Array.prototype.splice.call (b, 0)> Object.keys (c) Array ["1000", "1001"]> c Array [ ,,,,,,,,,,, 992 more ...] - zb '