如何在JSONArray中找到两个连续对象之间的最大和最小差异

时间:2016-02-05 06:07:51

标签: javascript arrays json

我有像

这样的JSON数据
{
    "data": [{
        "distance": "700",
        "name": "xyz"
    }, {
        "distance": "680",
        "name": "abc"
    }, {
        "distance": "670",
        "name": "lmn"
    }, {
        "distance": "620",
        "name": "pqr"
    }, {
        "distance": "400",
        "name": "tuv"
    }]
}

我想找到最大值&两个连续节点之间的最小距离。 我尝试了以下代码,但我不知道自己错过了什么 在这里,我试图利用jQuery排序来实现它。

var min = data[0].distance - data[1].distance,
    max = data[0].distance - data[1].distance;
data.sort(function (a, b) {
    var temp = a.distance - b.distance;
    if (temp > max)
        max = temp;
    if (temp < min)
        min = temp;
});

我甚至尝试使用普通的jQuery forEach循环

var min = data[0].distance - data[1].distance,
    max = data[0].distance - data[1].distance;
data.forEach(function (d, i) {
    var temp = data[i + 1].distance - d.distance;
    if (temp > max)
        max = temp;
    if (temp < min)
        min = temp;
});

2 个答案:

答案 0 :(得分:2)

你可以这样做:

// Set default values to the max and min, to compare them later
var min = Number.MAX_VALUE,
    max = Number.MIN_VALUE;

// Iterate over the data object
for (var i = obj.data.length - 2; i >= 0; i--) {
    // Get the absolute(ignoring negatives) difference
    var temp = Math.abs(obj.data[i].distance - obj.data[i + 1].distance);

    // update values accordingly
    min = Math.min(min, temp);
    max = Math.max(max, temp);
}
console.log(min, max);

&#13;
&#13;
var obj = {
    "data": [{
        "distance": "700",
        "name": "xyz"
    }, {
        "distance": "680",
        "name": "abc"
    }, {
        "distance": "670",
        "name": "lmn"
    }, {
        "distance": "620",
        "name": "pqr"
    }, {
        "distance": "400",
        "name": "tuv"
    }]
};

var min = Number.MAX_VALUE,
    max = Number.MIN_VALUE;
for (var i = obj.data.length - 2; i >= 0; i--) {
    var temp = Math.abs(obj.data[i].distance - obj.data[i + 1].distance);
    min = Math.min(min, temp);
    max = Math.max(max, temp);
}
console.log(min, max);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试一试。

var jsonData = {
    "data": [{
        "distance": "700",
        "name": "xyz"
    }, {
        "distance": "680",
        "name": "abc"
    }, {
        "distance": "670",
        "name": "lmn"
    }, {
        "distance": "620",
        "name": "pqr"
    }, {
        "distance": "400",
        "name": "tuv"
    }]
};
var maxData = 0;
var minData = 0;
var data = 0;
$.each(jsonData.data, function(i, obj) { 
    if(i==0)
    {
        minData = obj.distance;     
    }
    else
    {       
        data = jsonData.data[i-1].distance - obj.distance;      
       if(data > maxData)
            maxData = data;
       if(data < minData)
            minData = data; 
    }
}); 
console.log("Max : "+maxData);
console.log("Min : "+minData);