JavaScript Array Ranking - JavaScript


Suppose, we have three JavaScript arrays of Number like these −

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

The length of all the arrays will always be the same.

We are required to write a JavaScript function that in any number of such arrays maps the corresponding elements of an existing array according to their rank (i.e., their order in decreasing sense).

Therefore, for the above arrays, the output should look like −

const array1= [3,2,1,1,1,1,2,3,2,2,3];
const array2= [1,1,2,2,2,2,1,2,1,1,2];
const array3= [2,3,3,3,3,3,3,1,2,3,1];

Example

Following is the code −

const array1 = [10,23,53,74,33,56,6,0,43,45,11];
const array2 = [52,46,27,28,4,11,53,6,75,75,22];
const array3 = [26,18,10,12,31,12,5,8,44,34,65];
const transpose = (rank, arr) => {
   return arr.map((el, ind) => {
      return [...(rank[ind] || []), el];
   });
};
const ranks = arr => {
   return arr.map(
      Map.prototype.get,
      [...arr]
      .sort((a, b) => b - a)
      .reduce((r => (m, v) => m.set(v, (r++, m.get(v)) || r))(0), new Map)
   );
};
const findRanks = (...arrs) => {
   return arrs
   .reduce(transpose, [])
   .map(ranks)
   .reduce(transpose, []);
};
console.log(findRanks(array1, array2, array3));

Output

This will produce the following output on console −

[
 [
   3, 2, 1, 1, 1,
   1, 2, 3, 3, 2,
   3
 ],
 [
   1, 1, 2, 2, 3,
   3, 1, 2, 1, 1,
   2
 ],
 [
   2, 3, 3, 3, 2,
   2, 3, 1, 2, 3,
   1
 ]
]

Updated on: 01-Oct-2020

482 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements