Home  >  Article  >  Web Front-end  >  Constructing strings from character matrices and numeric arrays in JavaScript

Constructing strings from character matrices and numeric arrays in JavaScript

WBOY
WBOYforward
2023-08-24 08:17:02940browse

在 JavaScript 中基于字符矩阵和数字数组构造字符串

Question

We need to write a JavaScript function that accepts an n * n matrix of string characters and an array of integers (positive and unique).

Our function should construct a string consisting of characters that exist at a 1-based index in a numeric array.

Character matrix-

[
   [‘a’, ‘b’, ‘c’, d’],
   [‘o’, ‘f’, ‘r’, ‘g’],
   [‘h’, ‘i’, ‘e’, ‘j’],
   [‘k’, ‘l’, ‘m’, n’]
];

Numeric array-

[1, 4, 5, 7, 11]

should return "adore" because these are the characters that occur at the 1-based index specified by the numeric array in the matrix .

Example

The following is the code- p>

Live demonstration

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));

Output

The following is the console output-

adore

The above is the detailed content of Constructing strings from character matrices and numeric arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete