💾arr.topN()

👉 replit

// arr.topN(n, sort)
Array.prototype.topN = function(n, sortFunc=(a,b) => b-a){  
    return [...this]        // shallow copy
        .sort(sortFunc)
        .slice(0, n);
};

[1,2,3,3,4,4].topN(3),      // [ 4, 4, 3 ]
[1,2].topN(3),              // [ 2, 1 ]
[5,3,2,1,4].topN(3),        // [ 5, 4, 3 ]
[].topN(3),                 // []

['this', 'is', 'a', 'book'].topN(3, (a,b) => b.length - a.length),    
// [ 'this', 'book', 'is' ]

Last updated