在 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

更新於:20-Apr-2021

151 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.