排名数组元素 [英] Ranking array elements

查看:124
本文介绍了排名数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个算法,在Javascript中排名数组元素。

例子:我有一个数组如下:

  79,5,18,5,32,1,16,1,82,13]
 

我需要通过价值排名中的条目。所以,82应该得到1级,79级2等。 如果两个项目具有相同的价值,他们收到一个较低的数值提出了同样的等级和军衔。

因此​​对于本阵,新的排名阵列将是:

  [2,7,4,7,3,9,5,9,1,6]
 

我怎样才能做到这一点?

解决方案

  VAR ARR = [79,5,18,5,32,1,16,1,82,13] ;
VAR排序= arr.slice()排序(功能(A,B){返回巴})
。VAR等级= arr.slice()图(函数(V){返回sorted.indexOf(V)+1);
 

结果:

  [2,7,4,7,3,9,5,9,1,6]
 

如果你想用旧的浏览器兼容,您可能需要<一个href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf">define一个垫片对indexOf 和<一href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map">map (注意,如果你想做到这一点非常快非常大的数组,你最好使用循环并使用一个对象映射,而不是的indexOf )。

I need an algorithm to rank elements of an array in Javascript.

Example : I have an array as follows:

[79, 5, 18, 5, 32, 1, 16, 1, 82, 13]

I need to rank the entries by value. So 82 should receive rank 1, 79 rank 2 etc. If two entries have the same value they receive the same rank and the rank for a lower value is raised.

So for this array, the new ranking array would be:

[2, 7, 4, 7, 3, 9, 5, 9, 1, 6] 

How can I do this ?

解决方案

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

Result :

[2, 7, 4, 7, 3, 9, 5, 9, 1, 6]

If you want to be compatible with old browsers, you may have to define a shim for indexOf and for map (note that if you want to do this very fast for very big arrays, you'd better use for loops and use an object as map instead of indexOf).

这篇关于排名数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆