Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Determining rank on basis of marks in JavaScript
We are required to write a JavaScript function that takes in an array of numbers representing student marks and returns an array of ranks based on their performance.
The function should assign rank 1 to the highest marks, rank 2 to the second highest, and so on. Each student's rank corresponds to their position when marks are sorted in descending order.
Problem Statement
Given an array of marks, we need to determine the rank of each student based on how their marks compare to others in the class.
For example, if the input is:
const marks = [50, 47, 39, 32, 31];
The expected output should be:
const ranks = [1, 2, 3, 4, 5];
Solution Approach
The algorithm works by creating a sorted copy of the marks array in descending order, then finding each mark's position in this sorted array to determine its rank.
const marks = [50, 47, 39, 32, 31];
const findRanks = (arr = []) => {
const { length } = arr;
let sortedArray = arr.slice();
sortedArray.sort((a, b) => b - a);
const result = [];
for(let i = 0; i < length; i++){
const rank = sortedArray.indexOf(arr[i]);
result.push(rank + 1);
}
return result;
};
console.log(findRanks(marks));
[ 1, 2, 3, 4, 5 ]
Handling Duplicate Marks
Let's test the function with duplicate marks to see how it handles ties:
const marksWithDuplicates = [85, 92, 78, 92, 85, 90];
console.log("Original marks:", marksWithDuplicates);
console.log("Ranks:", findRanks(marksWithDuplicates));
Original marks: [ 85, 92, 78, 92, 85, 90 ] Ranks: [ 3, 1, 6, 1, 3, 2 ]
How It Works
-
Create a copy:
arr.slice()creates a shallow copy to avoid modifying the original array -
Sort descending:
sort((a, b) => b - a)arranges marks from highest to lowest -
Find positions:
indexOf()finds the first occurrence of each mark in the sorted array - Convert to rank: Add 1 to the index since ranks start from 1, not 0
Alternative Implementation
Here's a more efficient approach that handles ties by giving the same rank to equal marks:
const findRanksWithTies = (arr = []) => {
const uniqueMarks = [...new Set(arr)].sort((a, b) => b - a);
const rankMap = new Map();
uniqueMarks.forEach((mark, index) => {
rankMap.set(mark, index + 1);
});
return arr.map(mark => rankMap.get(mark));
};
const testMarks = [85, 92, 78, 92, 85, 90];
console.log("Marks:", testMarks);
console.log("Ranks with proper ties:", findRanksWithTies(testMarks));
Marks: [ 85, 92, 78, 92, 85, 90 ] Ranks with proper ties: [ 3, 1, 4, 1, 3, 2 ]
Conclusion
The ranking algorithm creates a sorted reference array and maps each original mark to its rank position. For handling ties properly, consider using a Map-based approach that assigns the same rank to equal marks.
