Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Constructing a string based on character matrix and number array in JavaScript
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 −
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
Advertisements