如果我的问题很愚蠢,我很抱歉。我一直在努力使用JavaScript在数组中获得最小值,即使数组大小为1.例如,如果我有数组由元素[1,1,3,4,1,2]组成],我想知道最小值是1,1,1,2,3,4,按此顺序。但是,我无法得到理想的结果。有人可以帮助我吗?
我有以下代码段:
var nearestBoothIndex = 0;
var arrDistanceToThisBooth = [1, 1, 3, 4, 1, 2];
var distanceToThisBoothLength = arrDistanceToThisBooth.length;
var nearestBooth = arrDistanceToThisBooth[0]
for (var a = 0; a < distanceToThisBoothLength; a++) {
if (arrDistanceToThisBooth.length == 1) {
nearestBooth = arrDistanceToThisBooth[0];
alert("nearest booth " + nearestBooth);
}
for (var b = 1; b < arrDistanceToThisBooth.length; b++) {
if (arrDistanceToThisBooth[b] <= nearestBooth) {
nearestBooth = arrDistanceToThisBooth[b]
alert("nearest booth " + nearestBooth);
nearestBoothIndex = b;
} else if (arrDistanceToThisBooth.length == 2 && (nearestBooth < arrDistanceToThisBooth[b])) {
nearestBooth = nearestBooth
nearestBoothIndex = 0;
alert("nearest booth " + nearestBooth);
}
}
var elementRemoved = arrDistanceToThisBooth.splice(nearestBoothIndex, 1);
}
&#13;
答案 0 :(得分:2)
如果要在存储原始索引的同时对数组进行排序,则必须将索引存储在对象中,或者将每个值转换为记住其索引的对象,然后使用自定义排序比较器。
function sortKeepingIndexes(values) {
return values
.map(function(val, i) { return { value: val, index: i }; })
.sort(function(a, b) { return a.value - b.value; });
}
var sorted = sortKeepingIndexes([1, 1, 3, 4, 1, 2]);
console.log(sorted);
&#13;
.as-console-wrapper { max-height: 100% !important; }
&#13;
最小值的索引为sorted[0].index
。
答案 1 :(得分:1)
var arr = [10, 1, 3, 4, 2, 1];
var arrCopy = arr.slice();
arrCopy.sort(function(a,b){
return a - b;
});
alert(arr + '\n' + arrCopy);
&#13;
可能是您需要的东西
答案 2 :(得分:0)
通过Array.sort
对数组进行排序会改变数组。这有时不是理想的结果。这似乎是你在这个特殊情况下想要的结果,但仅仅是FYI。
你也可以使用underscore
或lodash
个库...都有_.min
和_.max
方法(以及其他许多有用的方法)可以给你结果没有改变数组。