# arr.indexDictionaryForValues()

[JS](../../../..) ⟩ [objects](../../../obj) ⟩ [Array](..) ⟩ [methods](../method) ⟩ indexDictionaryForValues()

{% hint style="success" %}
主要用於找 [google-sheet](../../../../../appendix/gas/google-sheet "mention") 的<mark style="color:yellow;">**欄位索引**</mark> (column index)。
{% endhint %}

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

```javascript
/* 
 * 🔸 array.indexDictionaryForValues(values)
 * return the index for each value (a dictionary object)
 *
 * @example
 *
 *   let row = ["座號", "姓名", "國語文", "英語文"];
 *   row.indexDictionaryForValues(["座號", "姓名"]) // { '座號': 0, '姓名': 1 }
 */
Array.prototype.indexDictionaryForValues = function(values){
    
    let dict = {};
    
    for(const value of values){
        const i = this.indexOf(value);
        if(i < 0) throw new Error(`⛔ array.indexDictionaryForValues(): array doesn't have value "${value}"`);
        dict[value] = i;
    }
    
    return dict;
};
```

💈範例：

```javascript
let array = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
let row = ["座號", "姓名", "國語文", "英語文"];

array.indexDictionaryForValues([777, 22])        // { '22': 2, '777': 5 }
row.indexDictionaryForValues(["座號", "姓名"])    // { '座號': 0, '姓名': 1 }
// row.indexDictionaryForValues(["沒這個值"])     // ⛔ Error
```
{% endtab %}

{% tab title="⬇️ 應用" %}
* [class-average](../../../../../appendix/gas/projects/class-average "mention") - 用於找欄位索引 (column index)
* [guo-zhong-cheng-ji-yi-lan-biao](../../../../../appendix/gas/projects/guo-zhong-cheng-ji-yi-lan-biao "mention")
* [gas](../../../../../appendix/gas "mention") app [helpers](../../../../../appendix/gas/app/helpers "mention").
{% endtab %}
{% endtabs %}
