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

We need to write a JavaScript function that takes an n × n matrix of string characters and an array of integers (positive and unique), then constructs a string from characters at the specified 1-based positions.

Problem Understanding

Given a character matrix, we flatten it into a single array and extract characters at positions specified by the number array (using 1-based indexing).

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]

The flattened matrix becomes: ['a', 'b', 'c', 'd', 'o', 'f', 'r', 'g', 'h', 'i', 'e', 'j', 'k', 'l', 'm', 'n']

At 1-based positions [1, 4, 5, 7, 11], we get characters ['a', 'd', 'o', 'r', 'e'], forming the string "adore".

Solution

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 = []) => {
    // Flatten the 2D matrix into a single array
    const flat = [];
    arr.forEach(sub => {
        flat.push(...sub);
    });
    
    // Build result string by extracting characters at specified positions
    let res = '';
    pos.forEach(num => {
        res += (flat[num - 1] || ''); // Convert 1-based to 0-based index
    });
    
    return res;
};

console.log(buildString(arr, pos));
adore

Alternative Approach Using flat() Method

const buildStringAlt = (arr = [], pos = []) => {
    // Use built-in flat() method to flatten the matrix
    const flat = arr.flat();
    
    // Map positions to characters and join
    return pos.map(num => flat[num - 1] || '').join('');
};

console.log(buildStringAlt(arr, pos));
adore

How It Works

The solution works in two main steps:

  1. Flatten the matrix: Convert the 2D array into a 1D array using either manual iteration with spread operator or the built-in flat() method.
  2. Extract characters: For each position in the number array, subtract 1 (to convert from 1-based to 0-based indexing) and retrieve the character at that position.

Edge Case Handling

// Test with positions beyond matrix bounds
const testPos = [1, 4, 5, 20, 25]; // positions 20 and 25 don't exist

console.log(buildString(arr, testPos));
ado

The function handles invalid positions gracefully by using the logical OR operator || '', which returns an empty string for undefined positions.

Conclusion

This solution efficiently flattens a 2D character matrix and constructs strings based on 1-based position arrays. The approach handles edge cases and can be implemented using either manual flattening or the built-in flat() method.

Updated on: 2026-03-15T23:19:00+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements