![](/img/trans.png)
[英]How to get the unmatched array value from array in javascript with minimum complexity?
[英]Cannot get minimum value from Array (Javascript)?
我試圖從數組中獲取最小值,但我遇到了這種奇怪的行為。 我的期望是得到 89 作為最小距離,而不是我得到 100。誰能解釋一下?
// List
var nodes = {
"node": [
{
"name": "test",
"id": "2",
"edges": {
"edge": [
{
"to": "4",
"distance": "89"
},
{
"to": "6",
"distance": "100"
},
{
"to": "8",
"distance": "500"
}
]
}
}]
}
// Initialization
startNode = 0
currentNode = startNode;
edge = nodes.node[currentNode].edges.edge;
var minimumDistance = 99999;
// Loop through the Neighbors of one Node
for (x= 0; x<edge.length; x++) {
if (edge[x].distance < minimumDistance) {
minimumDistance = edge[x].distance;
}
document.write('Neighbor: ' + edge[x].to + ', Distance: ' + edge[x].distance);
document.write('</br>');
}
document.write('</br>');
document.write('Minimum Distance: ' + minimumDistance );
您需要使用數字而不是字符串進行比較。 比較字符串與數字不同。 下面是一些例子:
var nodes = { node: [{ name: "test", id: "2", edges: { edge: [{ to: "4", distance: "89" }, { to: "6", distance: "100" }, { to: "8", distance: "500" }] } }] }, startNode = 0, currentNode = startNode, edge = nodes.node[currentNode].edges.edge, minimumDistance = Infinity, // greatest value x; for (x = 0; x < edge.length; x++) { if (+edge[x].distance < minimumDistance) { // unary plus for getting a number minimumDistance = edge[x].distance; } document.write('Neighbor: ' + edge[x].to + ', Distance: ' + edge[x].distance); document.write('</br>'); } document.write('</br>'); document.write('Minimum Distance: ' + minimumDistance );
讓我們將其分解為最小代碼示例。 您正在(恕我直言過度嵌套) nodes
對象內的edge
數組中尋找屬性distance
的最小值。
問題是distance
值是字符串,而不是數字。 因此,應將這些值轉換為Number
以便能夠比較它們並確定distance
值的最小值。 現在使用+[a numeric string value]
將距離映射到Number
。
要確定最小值,您可以隨后將Math.min
應用於映射的數值數組。
const edge = [ { "to": "4", "distance": "89" }, { "to": "6", "distance": "100" }, { "to": "8", "distance": "500" } ]; // map distances to numeric values const distancesFromEdge = edge.map( val => +val.distance ); // determine the minimum value of the mapped values const minDistance = Math.min.apply(null, distancesFromEdge); console.log(minDistance);
正如羅賓指出的那樣-您正在比較字符串。 如果您無法在數據源中存儲整數,則可以使用parseInt()
執行以下操作;
if (parseInt(edge[x].distance) < minimumDistance) {
minimumDistance = parseInt(edge[x].distance);
}
將字符串更改為距離對象中的數字。
var nodes = {
"node": [
{
"name": "test",
"id": "2",
"edges": {
"edge": [
{
"to": "4",
"distance": 89
},
{
"to": "6",
"distance": 100
},
{
"to": "8",
"distance": 500
}
]
}
}]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.