Determining rank on basis of marks in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array, arr, of numbers as the only argument.

The array basically consists of the marks scored by some students, based on the array of marks, our function should prepare and return an array of ranks which should contain the rank of corresponding students on the basis of how high their marks are in the marks array arr.

For instance, for the highest entry in array arr, the corresponding entry in output array should be 1, 2 for second highest and so on.

For example, if the input to the function is −

const arr = [50, 47, 39, 32, 31];

Then the output should be −

const output = [1, 2, 3, 4, 5];

Output Explanation:

The marks in the array arr are already placed in decreasing order which means the highest marks are at the very first index and so on.

Example

The code for this will be −

 Live Demo

const arr = [50, 47, 39, 32, 31];
const findRanks = (arr = []) => {
   const { length } = arr;
   let sortArray = arr.slice();
   sortArray.sort((a,b) => b - a);
   const result = [];
   for(let i = 0; i < length; i++){
      const j = sortArray.indexOf(arr[i])
      result.push(j + 1);
   }
   return result;
};
console.log(findRanks(arr));

Output

And the output in the console will be −

[ 1, 2, 3, 4, 5 ]
raja
Published on 03-Mar-2021 10:41:33
Advertisements