Yùz*_*ami 17 javascript arrays sorting algorithm ranking
我需要一个算法来在Javascript中对数组的元素进行排名.
示例:我有一个数组如下:
[79, 5, 18, 5, 32, 1, 16, 1, 82, 13]
Run Code Online (Sandbox Code Playgroud)
我需要按值对条目进行排名.因此,82应该获得等级1,79等级2等.如果两个条目具有相同的值,则它们接收相同的等级,并且提高较低值的等级.
所以对于这个数组,新的排名数组将是:
[2, 7, 4, 7, 3, 9, 5, 9, 1, 6]
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点 ?
Den*_*ret 30
var arr = [79, 5, 18, 5, 32, 1, 16, 1, 82, 13];
var sorted = arr.slice().sort(function(a,b){return b-a})
var ranks = arr.slice().map(function(v){ return sorted.indexOf(v)+1 });
Run Code Online (Sandbox Code Playgroud)
结果:
[2, 7, 4, 7, 3, 9, 5, 9, 1, 6]
Run Code Online (Sandbox Code Playgroud)
如果你想与旧的浏览器兼容,你可能必须为indexOf和map 定义一个垫片(注意,如果你想对非常大的数组做这么快,你最好使用for循环并使用一个对象作为map而不是indexOf).
这不适用于旧浏览器,因为它使用ECMAScript 5功能,但它允许您快速简洁地生成排名数组,即使对于非常大的数组也是如此.(它不使用indexOf哪种线性搜索,因此对于大型数组来说可能很慢.)
function cmp_rnum(a,b) {
// comparison function: reverse numeric order
return b-a;
}
function index_map(acc, item, index) {
// reduction function to produce a map of array items to their index
acc[item] = index;
return acc;
}
function ranks(v) {
var rankindex = v.slice().sort(cmp_rnum).reduceLeft(index_map, Object.create(null));
// reduceLeft() is used so the lowest rank wins if there are duplicates
// use reduce() if you want the highest rank
return v.map(function(item){ return rankindex[item]+1; });
}
Run Code Online (Sandbox Code Playgroud)
示例输出:
> ranks([79, 5, 18, 5, 32, 1, 16, 1, 82, 13]);
[2, 7, 4, 7, 3, 9, 5, 9, 1, 6]
Run Code Online (Sandbox Code Playgroud)