> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/builtin/arr/ext/arr.rank.md).

# arr.rank()

[JS](/web/js.md) ⟩ [objects](/web/js/val/obj.md) ⟩ [Array](/web/js/val/builtin/arr.md) ⟩ [methods](/web/js/val/builtin/arr/method.md) ⟩ rank()

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit: [arr.rank()](https://replit.com/@pegasusroe/arrrank#index.js)

```javascript
// 🔸 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;
};
```

💈範例：

```javascript
const players = [
    { nickname: "Bob"  , score: 100 },
    { nickname: "Amy"  , score: 200 },
    { nickname: "Grant", score: 300 },
    { nickname: "Steve", score: 200 },
    { nickname: "Joe"  , score: 500 },
];

console.log(players.rank((a,b) => b.score - a.score));
// [
//   { nickname: 'Joe'  , score: 500, rank: 1 },
//   { nickname: 'Grant', score: 300, rank: 2 },
//   { nickname: 'Amy'  , score: 200, rank: 3 },
//   { nickname: 'Steve', score: 200, rank: 3 },
//   { nickname: 'Bob'  , score: 100, rank: 4 }    // ⭐️ consecutive rank
// ]

console.log(players.rank((a,b) => b.score - a.score, false));
// [
//   { nickname: 'Joe'  , score: 500, rank: 1 },
//   { nickname: 'Grant', score: 300, rank: 2 },
//   { nickname: 'Amy'  , score: 200, rank: 3 },
//   { nickname: 'Steve', score: 200, rank: 3 },
//   { nickname: 'Bob'  , score: 100, rank: 5 }    // ⭐️ rank 4 is skipped.
// ]

console.log(players);
// [
//   { nickname: 'Bob'  , score: 100, rank: 5 },    // in original order
//   { nickname: 'Amy'  , score: 200, rank: 3 },
//   { nickname: 'Grant', score: 300, rank: 2 },
//   { nickname: 'Steve', score: 200, rank: 3 },
//   { nickname: 'Joe'  , score: 500, rank: 1 }
// ]
```

{% endtab %}

{% tab title="⬇️ 應用" %}

* [國中成績一覽表](/web/appendix/gas/projects/guo-zhong-cheng-ji-yi-lan-biao.md) - 用於計算<mark style="color:yellow;">**班排**</mark>、<mark style="color:yellow;">**校排**</mark>。
  {% endtab %}

{% tab title="🗣 討論" %}

* [How to rank objects by property?](https://stackoverflow.com/questions/35737274/how-to-rank-objects-by-property)
  {% endtab %}

{% tab title="👥 相關" %}

* [arr.entries](/web/js/val/builtin/arr/method/arr.entries.md)
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/val/builtin/arr/ext/arr.rank.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
