Introduction
In this lab, we will be exploring the concept of array ranking in JavaScript. The purpose of this lab is to understand how to calculate the ranking of an array based on a comparator function, using techniques such as Array.prototype.map() and Array.prototype.filter(). Through practical examples and exercises, you will gain a better understanding of how to implement this functionality in your own JavaScript projects.
Ranking Arrays
To practice coding, open the Terminal/SSH and type node. This function calculates the ranking of an array based on a comparator function.
To use this function, you can:
- Use
Array.prototype.map()andArray.prototype.filter()to map each element to a rank using the provided comparator function.
Here's an example usage:
const ranking = (arr, compFn) =>
arr.map((a) => arr.filter((b) => compFn(a, b)).length + 1);
Example:
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]
Summary
Congratulations! You have completed the Array Ranking lab. You can practice more labs in LabEx to improve your skills.