Home > Enterprise >  Is there a better approach to count sportsmens rating?
Is there a better approach to count sportsmens rating?

Time:10-15

I have a code that count sportsmens rating , for example if you have same rating as person before you will have same score number :

    import "./styles.css";

export default function App() {
  const ratingScore = [100, 90, 90, 90, 80, 70, 60, 50, 50, 50, 50, 40];

  const getRatingNum = (rating) => {
    const ratingScore = [];
    rating.forEach((el, i, arr) => {
      if (i === 0) {
        ratingScore.push(1);
        return;
      }

      if (arr[i - 1] > el) {
        const newScore = ratingScore.at(-1)   1;
        ratingScore.push(newScore);
        return;
      }

      if (arr[i - 1] === el) {
        const newScore = ratingScore.at(-1);
        ratingScore.push(newScore);
        return;
      }
    });

    return ratingScore;
  };

  return (
    <div className="App">
      {ratingScore.map((el, i) => {
        return (
          <p key={Math.random() * 10}>
            {getRatingNum(ratingScore)[i]}. {el}
          </p>
        );
      })}
    </div>
  );
}

link to live example - Codesandbox Demo

import React from 'react';

export default function App() {
    const ratingScore = [100, 90, 90, 90, 80, 70, 60, 50, 50, 50, 50, 40];

    const getRatingNum = ( rating ) => {
        let result = [], count = 0;
        ratingScore.forEach( ( n ) => {
            if (!result.length || result[result.length - 1].key !== n) result.push( { key: n, count:   count } );
            else result.push( { key: n, count: result[result.length - 1].count } );
        } );

        return result;
    };

    return (
        <div className="App">
        {
            getRatingNum(ratingScore).map((o, i) => {
                return (
                    <p key={i}>{o.count}. {o.key}</p>
                )
            })
        }
        </div>
    );
}

CodePudding user response:

What about such simple approach (pseudocode):

 let ratings = [1], curr_rating = 1

 for (let i = 1; i < ratingScore.length; i  ) {
    if ratingScore[i] < ratingScore[i - 1] {
          curr_rating  
       }
    ratings.push(curr_rating)
 }
  • Related