gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:04:16 25 4
gpt4 key购买 nike

我有一个 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;
});

最佳答案

你可以这样做:

// 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);

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);

关于javascript - 如何找到 JSONArray 中两个连续对象之间的最大和最小差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35217374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com