💾arr.indexDictionaryForValues()

JSobjectsArraymethods ⟩ indexDictionaryForValues()

💾 replit

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

💈範例:

Last updated

Was this helpful?