Home > Web Front-end > JS Tutorial > body text

Constructing strings from character matrices and numeric arrays in JavaScript

WBOY
Release: 2023-08-24 08:17:02
forward
930 people have browsed it

在 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’]
];
Copy after login

Numeric array-

[1, 4, 5, 7, 11]
Copy after login

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-

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));
Copy after login

Output

The following is the console output-

adore
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!