在此示例中,如何通过层次排序(1. 306,2. 267,3. 263)获取最大3个值的列表或数组?数组内的最高计数循环
var array = [267, 306, 108, 263, 67];
var largest = Math.max.apply(Math, array); // 306
在此示例中,如何通过层次排序(1. 306,2. 267,3. 263)获取最大3个值的列表或数组?数组内的最高计数循环
var array = [267, 306, 108, 263, 67];
var largest = Math.max.apply(Math, array); // 306
您需要从最大到最小排序,然后切分前三项。
var arr = [267, 306, 108, 263, 67];
console.log(arr.sort((a, b) => b - a).slice(0, 3));
.as-console-wrapper { top: 0; max-height: 100% !important; }
谢谢。工作正常。但是这些值是指一个字符串,我不知道如何在排序后将它引用到该值。我已将它添加到值的后面(使用+'string'),但排序并不有用。任何解决方案 – user3236072
是的,使用:'(a,b)=> b.localeCompare(a)'或'parseInt(b,10) - parseInt(a,10)'。 –
太棒了! :) 谢谢。 – user3236072
您可以使用Array.sort() 和Array.slice() 方法来得到你想要的。
var array = [267, 306, 108, 263, 67];
var sorted = array.sort(function(a,b) { return b - a }); // sort the array in descending order
var largest = sorted.slice(0, 3); // get first three array elements
console.log(largest); // Array [ 306, 267, 263 ]
你的答案应该是精确和可用的。如果你给出了一些指导[不是确切的答案],那么使用评论,而不是作为答案。 –
感谢提示 –
欢迎。但你的回答与@Mr相同。 polywhril。相同的答案应该被标记为重复,并且应该被删除。 –
你可以把它想:
var array = [267, 306, 108, 263, 67];
findLargest3();
function findLargest3(){
// sort descending
array.sort(function(a,b){
if(a < b){ return 1; }
else if(a == b) { return 0; }
else { return -1; }
});
alert(array.slice(0, 3));
}
你可以写一个辅助函数,就像这样:
function getTopItems(arr, howMany, comparator) {
if (typeof comparator !== "function") {
comparator = function(a, b) {return a > b;};
}
function addToOutput(item) {
var previous = item;
var found = false;
for (var innerIndex = 0; innerIndex < output.length; innerIndex++) {
if (found) {
var aux = previous;
previous = output[innerIndex];
output[innerIndex] = aux;
} else if (comparator(item, output[innerIndex])) {
found = true;
var aux = previous;
previous = output[innerIndex];
output[innerIndex] = aux;
}
console.log(output);
}
if (output.length < howMany) output.push(previous);
}
var index = 0;
var output = [];
while (index < arr.length) {
addToOutput(arr[index++]);
}
return output;
}
可能重复的http://计算器。 com/questions/1063007/how-to-sort-an-array-of-correctly –