data object

I just can not remember how to return one of these objects with the minimum distance value, tell me how to implement plz. Math.min ? or may find ?

  for (let point of this.points){ const res = {title: point.title, distance : point.getDistance(x,y,z).toFixed(0)}; console.log(res); } 

    2 answers 2

     let data = [{ title: 'a', distance: '193' }, { title: 'b', distance: '1175' }, { title: 'c', distance: '365' } ] let res = data.reduce((res, point) => { if (parseInt(point.distance) < parseInt(res.distance)) res = point; return res; }); console.log(res); 

    • assign res, in this case, it is not necessary, it is enough to immediately return the point, in which case the function will become single-line: (res, point) => (parseInt(point.distance) < parseInt(res.distance)) ? point:res (res, point) => (parseInt(point.distance) < parseInt(res.distance)) ? point:res - Grundy
    • Yes, I, in principle, thought about it, but decided that it would be a little clearer. :) - Yaant 6:39 pm
    • reduce method is of course necessary. It is necessary to study and take note, thank you! - Sindr0me
     let min = {title: 'Not found', distance: Number.POSITIVE_INFINITY}; for (let point of this.points){ const res = {title: point.title, distance: point.getDistance(x,y,z).toFixed(0)}; if(res.distance < min.distance) min = res; } return min; 
    • one
      Here only toFixed() returns a string, respectively, next is a comparison of strings with all the resulting surprises. :) - Yaant