๐Ÿ’พarr.rank()

JS โŸฉ objects โŸฉ Array โŸฉ methods โŸฉ rank()

๐Ÿ’พ replit: arr.rank()arrow-up-right

// ๐Ÿ”ธ arr.rank()
Array.prototype.rank = function(compare, consecutiveRanks=true, rankPropertyName='rank'){

  const sorted = this
      .slice()            // copy the array
      .sort(compare);     // sort array of objects (in place)
    
  let current;            // object keeping the current rank

  // ๐Ÿงจ Note๏ผš
  // - indices (keys) of array.entries() are "integer-based"
  // - indices (keys) of Object.entries(array) are "string-based"โ—โ—โ—
  for(const [i, obj] of sorted.entries()){  

    // if not the same, generate new rank
    if (!current || compare(current, obj) !== 0) {
      obj[rankPropertyName] = (
          !consecutiveRanks ? i + 1 :        // ranks may have "gaps"
          !current          ?     1 :        // first rank
          current[rankPropertyName] + 1      // consecutive ranks
      );
      current = obj;
    }
        
    // if the same, use the current rank.
    else {
      obj[rankPropertyName] = current[rankPropertyName];
    }

  }

  return sorted;
};

๐Ÿ’ˆ็ฏ„ไพ‹๏ผš

Last updated

Was this helpful?