Capitalize letter in a string in order and create an array to store - JavaScript

We are required to write a JavaScript function that takes in a string and turns it into a Mexican Wave i.e. resembling string produced by successive capital letters in every word.

For example, if the string is:

const str = 'edabit';

Then the output should be the following with successive single capital letters:

const output = ["Edabit", "eDabit", "edAbit", "edaBit", "edabIt", "edabiT"];

Method 1: Using String Prototype Extension

This approach extends the String prototype with a custom replaceAt method:

const str = 'edabit';

const replaceAt = function(index, char) {
    let a = this.split("");
    a[index] = char;
    return a.join("");
};

String.prototype.replaceAt = replaceAt;

const createWave = word => {
    let array = word.split('');
    const res = array.map((letter, i) => {
        let a = word.replaceAt(i, letter.toUpperCase());
        return a;
    });
    return res;
}

console.log(createWave(str));
[ 'Edabit', 'eDabit', 'edAbit', 'edaBit', 'edabIt', 'edabiT' ]

Method 2: Using Slice Method (Modern Approach)

A cleaner approach without modifying the prototype:

const createMexicanWave = (str) => {
    const result = [];
    
    for (let i = 0; i 

[ 'Edabit', 'eDabit', 'edAbit', 'edaBit', 'edabIt', 'edabiT' ]

Method 3: Using Array.map()

A functional programming approach using map():

const createWaveWithMap = (str) => {
    return str.split('').map((char, index) => {
        return str.substring(0, index) + char.toUpperCase() + str.substring(index + 1);
    });
};

const str = 'hello';
console.log(createWaveWithMap(str));
[ 'Hello', 'hEllo', 'heLlo', 'helLo', 'hellO' ]

Comparison

Method Modifies Prototype Readability Performance
Prototype Extension Yes Good Good
Slice Method No Excellent Best
Array.map() No Very Good Good

Conclusion

The Mexican Wave pattern creates an array where each element has one character capitalized in sequence. The slice method is recommended as it's clean, readable, and doesn't modify built-in prototypes.

Updated on: 2026-03-15T23:18:59+05:30

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements