將字串中的字母對映到陣列物件 - JavaScript
給定一個字串,我們需要編寫一個函式,該函式建立一個物件,用於將每個字母的索引儲存在一個數組中。字串的字母(元素)必須是物件的鍵
索引應該儲存在一個數組中,這些陣列則是值。
例如 −
如果輸入字串為 −
const str = 'cannot';
則輸出應為 −
const output = {
'c': [0],
'a': [1],
'n': [2, 3],
'o': [4],
't': [5]
};示例
以下為程式碼 −
const str = 'cannot';
const mapString = str => {
const map = {};
for(let i = 0; i < str.length; i++){
if(map.hasOwnProperty(str[i])){
map[str[i]] = map[str[i]].concat(i);
}else{
map[str[i]] = [i];
};
};
return map;
};
console.log(mapString(str));輸出
以下是控制檯中的輸出 −
{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP