HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Calculate the ranking of a JavaScript array

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptrankingcalculatethearray

Problem

The ranking of an array is a list of the positions of its elements, based on a comparator function. This can be useful for sorting algorithms or ranking items in a list for display purposes.
In order to implement this, you can use Array.prototype.map() to iterate over each element and map it to its ranking. In order to calculate the ranking, you can use Array.prototype.filter() to count the number of elements that are smaller than the current element, based on the provided comparator function, compFn.

Solution

const ranking = (arr, compFn) =>
  arr.map(a => arr.filter(b => compFn(a, b)).length + 1);

ranking([8, 6, 9, 5], (a, b) => a < b);
// [2, 3, 1, 4]
ranking(['c', 'a', 'b', 'd'], (a, b) => a.localeCompare(b) > 0);
// [3, 1, 2, 4]

Code Snippets

const ranking = (arr, compFn) =>
  arr.map(a => arr.filter(b => compFn(a, b)).length + 1);

ranking([8, 6, 9, 5], (a, b) => a < b);
// [2, 3, 1, 4]
ranking(['c', 'a', 'b', 'd'], (a, b) => a.localeCompare(b) > 0);
// [3, 1, 2, 4]

Context

From 30-seconds-of-code: array-ranking

Revisions (0)

No revisions yet.