Home > Article > Web Front-end > Constructing strings from character matrices and numeric arrays in JavaScript
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 .
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));
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!