计数循环以获取数组中的值

时间:2017-05-15 10:28:14

标签: javascript

在这个例子中,如何通过层次排序(1. 306,2。267,3.363)获取最大3个值的列表或数组?

var array = [267, 306, 108, 263, 67];
var largest = Math.max.apply(Math, array); // 306

4 个答案:

答案 0 :(得分:4)

您需要从最大到最小排序然后切前三项。



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




答案 1 :(得分:0)

您可以使用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 ]

答案 2 :(得分:0)

你可以这样:

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

}

工作Js Fiddle

答案 3 :(得分:0)

您可以编写一个辅助函数,如下所示:

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