1

In this example, how to get a list or an array of the largest 3 values by an ‎hierarchic ordering (1. 306, 2. 267, 3. 263)?

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

4 Answers4

4

You need to sort largest to smallest then slice the top three items.

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; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

You might use Array.sort() and Array.slice() methods to get what you want.

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 ]
Marcin Pevik
  • 163
  • 1
  • 14
0

You can get it like:

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

}

Working Js Fiddle

Sagar Arora
  • 1,743
  • 1
  • 10
  • 19
0

You can write a helper function, like this:

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;
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175