在包含对象的数组中查找最小值、最大值

Find min, max in array with objects

我有这个数组,里面有对象:

var pts = [
    { "X": 52.67528921580262,  "Y": 8.373513221740723 },
    { "X": 52.6759657545252,   "Y": 8.374114036560059 },
    { "X": 52.682574466310314, "Y": 8.37256908416748  },
    { "X": 52.68356308524067,  "Y": 8.373942375183105 },
    { "X": 52.68293869694087,  "Y": 8.375487327575684 },
    { "X": 52.67685044320001,  "Y": 8.376259803771973 },
    { "X": 52.6756535071859,   "Y": 8.379607200622559 },
    { "X": 52.676017795531436, "Y": 8.382096290588379 },
    { "X": 52.68101344348877,  "Y": 8.380722999572754 },
    { "X": 52.68351105322329,  "Y": 8.383641242980957 },
    { "X": 52.68,              "Y": 8.389             }
];

如何找到 X 的最小值、最大值和 Y 的最小值、最大值?

您可以调用 Math.minMath.max,传入仅包含相关值的映射数组,如下所示:

function endProp( mathFunc, array, property ) {
    return Math[ mathFunc ].apply(array, array.map(function ( item ) {
        return item[ property ];
    }));
}

var maxY = endProp( "max", pts, "Y" ), // 8.389
    minY = endProp( "min", pts, "Y" ); // 8.37256908416748

排序数组可能是最简单的。

array.sort(function minXToMaxX(a,b){
   return a.x - b.x;
});

最低 x 值在 array[0]。最高 x 值位于 array[array.length - 1];

这段代码工作正常。请参阅演示片段。

var pts = [{
  "X": 52.67528921580262,
  "Y": 8.373513221740723
}, {
  "X": 52.6759657545252,
  "Y": 8.374114036560059
}, {
  "X": 52.682574466310314,
  "Y": 8.37256908416748
}, {
  "X": 52.68356308524067,
  "Y": 8.373942375183105
}, {
  "X": 52.68293869694087,
  "Y": 8.375487327575684
}, {
  "X": 52.67685044320001,
  "Y": 8.376259803771973
}, {
  "X": 52.6756535071859,
  "Y": 8.379607200622559
}, {
  "X": 52.676017795531436,
  "Y": 8.382096290588379
}, {
  "X": 52.68101344348877,
  "Y": 8.380722999572754
}, {
  "X": 52.68351105322329,
  "Y": 8.383641242980957
}, {
  "X": 52.68,
  "Y": 8.389
}];
var xobj = [];
var yobj = [];
var len = pts.length;

for (var i = 0; i < len; i++) {

  xobj.push(parseFloat(pts[i].X));
  yobj.push(parseFloat(pts[i].Y));
}

//height x value
var value = xobj[0];
for (var n = 1; n < xobj.length; n++) {
  if (xobj[n] > value) {
    value = xobj[n];
  }
}

//lowest x value
var valuel = xobj[0];
for (var n = 1; n < xobj.length; n++) {
  if (xobj[n] < valuel) {
    valuel = xobj[n];
  }
}

//height y value
var valueY = yobj[0];
for (var n = 1; n < yobj.length; n++) {
  if (yobj[n] > valueY) {
    valueY = yobj[n];
  }
}

//lowest x value
var valuelY = yobj[0];
for (var n = 1; n < yobj.length; n++) {
  if (yobj[n] < valuelY) {
    valuelY = yobj[n];
  }
}

document.getElementById("demo").innerHTML = valuel

document.getElementById("demo1").innerHTML = value

document.getElementById("demo2").innerHTML = valuelY

document.getElementById("demo3").innerHTML = valueY
Minx:
<p id="demo"></p>
MaxX:
<p id="demo1"></p>
Miny:
<p id="demo2"></p>
MaxY:
<p id="demo3"></p>