简体   繁体   中英

JavaScript Array Ranking

I have an Arrays like below in javascript:

var array1 = [10,23,53,74,33,56,6,0,43,45,11];
var array2 = [52,46,27,28,4,11,53,6,75,75,22];
var array3 = [26,18,10,12,31,12,5,8,44,34,65];
...
n number of array

So I want these array in Ranking format. Let's say
array1[0] = 10
array2[0] = 52
array3[0] = 26
so in the above example 52 is the highest value so it will replace as a 1 and 26 is the second highest value it will be replace with 2 and 10 is the third highiest value so it will replace as 3 and so on...

So the result of above example is:
var array1= [3];
var array2 = [1];
var array3 = [2];

And the whol arrays result will be as below:

var array1= [3,2,1,1,1,1,2,3,2,2,3];
var array2= [1,1,2,2,2,2,1,2,1,1,2];
var array3= [2,3,3,3,3,3,3,1,2,3,1];
...
n number of array

I have tried this with creating a parent array and keeping all sub arrays into parent and I have used multiple for loops to iterating sub arrays

You could take a chained approach by

  • transpose the data,
  • map the ranks for each array,
  • transpose again.

transpose is a litte function which takes an array of arrays and returns the switched values of cols in a row.

ranks takes an array, and maps the positions of the sorted array. This function creates inside a Map of values with the assigned ranks.

 var transpose = (r, a) => a.map((v, i) => [...(r[i] || []), v]), ranks = array => array.map( Map.prototype.get, [...array].sort((a, b) => b - a).reduce((r => (m, v) => m.set(v, (r++, m.get(v)) || r))(0), new Map) ), array1 = [10, 23, 53, 74, 33, 56, 6, 0, 43, 45, 11], array2 = [52, 46, 27, 28, 4, 11, 53, 6, 75, 75, 22], array3 = [26, 18, 10, 12, 31, 12, 5, 8, 44, 34, 65], result = [array1, array2, array3].reduce(transpose, []).map(ranks).reduce(transpose, []); result.forEach(a => console.log(...a));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM