Constructing a string based on character matrix and number array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an n * n matrix of string characters and an array of integers (positive and unique).

Our function should construct a string of those characters whose 1-based index is present in the array of numbers.

Character Matrix −

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

Number Array −

[1, 4, 5, 7, 11]

Should return ‘adore’ because these are the characters present at the 1-based indices specified by number array in the matrix.

Example

Following is the code −

 Live Demo

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

Following is the console output −

adore
raja
Published on 20-Apr-2021 08:15:13
Advertisements