在 JavaScript 中基於字元矩陣和數字陣列構造字串
問題
我們需要編寫一個 JavaScript 函式,該函式輸入一個字串字元的 n * n 矩陣和一個整數陣列(正數且唯一)。
我們的函式應構造一個字串,其中那些字元的基於 1 的索引存在於數字陣列中。
字元矩陣 −
[ [‘a’, ‘b’, ‘c’, d’], [‘o’, ‘f’, ‘r’, ‘g’], [‘h’, ‘i’, ‘e’, ‘j’], [‘k’, ‘l’, ‘m’, n’] ];
數字陣列 −
[1, 4, 5, 7, 11]
應返回“adore”,因為這些是矩陣中數字陣列指定的基於 1 的索引處存在的字元。
示例
以下是程式碼 −
const arr = [
['a', 'b', 'c', 'd'],
['o', 'f', 'r', 'g'],
['h', 'i', 'e', 'j'],
['k', 'l', 'm', 'n']
];
const pos = [1, 4, 5, 7, 11];
const buildString = (arr = [], pos = []) => {
const flat = [];
arr.forEach(sub => {
flat.push(...sub);
});
let res = '';
pos.forEach(num => {
res += (flat[num - 1] || '');
});
return res;
};
console.log(buildString(arr, pos));輸出
以下是控制檯輸出 −
adore
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP