Transform all characters in a string to uppercase sequentially and then save them in an array

// Let's create a fun and unique function that transforms a simple string into an exciting Mexican Wave!
var smallarr=[]
var   bigarr=[]
var   another=""

function wave(str){
    for (var i=0;i<str.length;i++){
        smallarr.push(str)
    }
    for (var j=0;j<smallarr.length;j++)
    {
        if(smallarr[j][j].toUpperCase()==smallarr[j][j])
        { 
            var c=smallarr[j][j].toLowerCase()
            smallarr[j][j]=c
        }
        else {
            var c=smallarr[j][j].toUpperCase()
            smallarr[j][j]=c}
        }        
    }
    return smallarr     
}

document.write(wave("edabit"))
//console.log(smallarr)

Instead of a regular wave, the original output was not as expected. For example: wave("edabit") ➞ ["Edabit", "eDabit", "edAbit", "edaBit", "edabIt", "edabiT"] but it returned the same as the input.

If you have any suggestions or advice on improving this function, feel free to share!

Answer №1

To transform the input string, you can divide it into individual characters and then iterate over each element to replace it with its uppercase equivalent:

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

console.log(convertToWave('hello'));

Answer №2

If you want to transform a string into an array, you can utilize the Array.from() method. Within the callback function (mapFn), extract the current letter and index, then use them along with String.substring() to construct a new string with the capitalized letter.

const alterString = str => Array.from(str, (char, index) =>
  str.substring(0, index) + char.toUpperCase() + str.substring(index + 1)
);

const updatedStr = alterString('hello');

console.log(updatedStr);

Answer №3

If you want to experiment with Array.map(), consider using the second callback parameter to represent an index:

let input = "coding";

let result = input.split('').map(
     (_, i) => input.split('').map(
          (char, j) => i === j ? char.toUpperCase() : char).join()
 );

console.log(result);

UPDATE:

An issue with your method is that strings are immutable, so a new string should be constructed using slice as shown below:

var smallarr=[]
   var bigarr=[]
   var another=""
   function wave(str){
    for (var i=0;i<str.length;i++){
         smallarr.push(str)
      }

     for (var j=0;j<smallarr.length;j++){
       smallarr[j] = smallarr[j].slice(0,j) + smallarr[j][j].toUpperCase() + smallarr[j].slice(j+1);
     }
   return smallarr     
   }

  document.write(wave("coding"))
  console.log(smallarr)

Alternatively, achieve the same result with just one loop:

   function wave(str){
    var smallarr=[]
    for (var i=0;i<str.length;i++){
         smallarr.push(str.slice(0,i) + str[i].toUpperCase() + str.slice(i+1))
      }
     return smallarr     
   }
  console.log(wave("coding"))

Answer №4

Your code faces a key issue where you attempt to update a character within a string, which is not feasible due to the immutability of strings in JavaScript. Assigning a value to a specific index will not alter the original string.

The recommended approach is to reconstruct a new string with the desired modifications. You can utilize the slice method to extract portions of the string and construct the updated version.

Below is your code modified to address this limitation:

function transformString(str) {
    var newArr = []; // declare as local variable
    for (var i = 0; i < str.length; i++) {
        let char = str[i]; // Introduce a variable to prevent redundancy
        if (char.toUpperCase() === char) {
            char = char.toLowerCase();
        } else {
            char = char.toUpperCase()
        }
        // String manipulation directly is restricted; necessitating generation of a new string
        newArr.push(str.slice(0, i) + char + str.slice(i+1));
    }
    return newArr;
}

console.log(transformString("example"));

Answer №5

Function.prototype.swapCase=function(index, char) {
    var arr = this.split("");
    arr[index] = char;
    return arr.join("");
}

const modifyString = ( text ) => {
  console.log('text ' + text.split(''));
  let array = text.split('')
  array.map((letter, i) => {
      let modified = text.swapCase(i, letter.toUpperCase());
      console.log(modified);
      return modified;
    });
    console.log(array)
    
   // console.log(text)
}

modifyString('example');

Answer №6

One way to manipulate a string is to split it, map the array and then check the index before applying an upper case letter to matching indices.

const
    modifyString = (str) => str
        .split('')
        .map((_, i, splitted) => splitted.map((char, j) => i === j ? char.toUpperCase() : char).join(''));
    };

console.log(modifyString('edabit'));

An alternative method

function transformString(string) {
    var result = [],
        i, j, temp;

    for (i = 0; i < string.length; i++) {
        temp = '';
        for (j = 0; j < string.length; j++) {
            temp += i === j ? string[j].toUpperCase() : string[j];
        }
        result.push(temp);
    }

    return result;
}

console.log(transformString('edabit'));

Answer №7

For smaller arrays, an efficient method involves utilizing the split, map, and join functions as shown below:

let word = `edabit`;

let output = word.split('').map((char,index,arr)=>{
  let tempArr = [...arr];
  tempArr[index]=tempArr[index].toUpperCase();
  return tempArr.join('');
});

console.log(output);

However, this approach is not optimized for larger arrays.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to connect the value of my range slider input to the corresponding input field in the HTML table?

I'm currently working with Django formsets. Within my HTML table body, I have a range slider. As of now, when I move the slider, it updates the last text box in the table as intended (with JavaScript handling this). However, what I want is for each s ...

Looking for a way to store data in local storage so it remains even after the page is reloaded? I tried adding a local storage function, but it doesn't appear to be

I am currently working on a project involving a work day scheduler and I am facing challenges in saving data within the schedule events, like at 8am, and making sure it persists on reload. The colored time block element that changes as hours pass in the da ...

The evaluate function is not functioning as expected

Code: console.log(propertyName); console.log(eval(this.state.propertyName)) console.log(this.state.DriverFirstName); Output: DriverFirstName undefined fsdfds I am attempting to access a variable defined by a string value (propertyNa ...

Encountered an unexpected issue: Attempting to convert a circular structure to JSON. Can you identify the root cause of

There seems to be an error with the form submission: The form is not updating in the database. The following error is being displayed. const handleAddItem = (event) => { event.preventDefault(); const productName = productNameRef.current.value; ...

Utilize textarea for dynamically populating an Array using jQuery

(JQUERY) I'm encountering an issue with populating an array from a textarea on my page. I am struggling with the formatting required for the array and how to use "split" to achieve this. Can anyone guide me through the process of populating the array ...

Using SceneJS to recycle JSON object nodes

I've utilized the scenejs framework to develop a webgl animation that includes numerous identical elements. To optimize code efficiency and reuse elements whenever necessary, I'm looking to minimize redundant code usage. Initially, I've def ...

Using JQuery and CSS to handle multiple hyperlink links with a single action

UPDATE: Issue resolved, thanks for the help. It is working fine now: http://jsfiddle.net/c3AeN/1/ by Sudharsan I have multiple links on my webpage, all in a similar format like this: note: When I say 'similar format', I mean that all links share ...

A step-by-step guide on how to use ajax/jquery to access an external webpage without relying on iframe

Is there a more effective way to call another page, such as http://www.google.com, and load it into my specific div without using an iframe? I attempted to do so with ajax... $.ajax({ url : 'http://www.google.com', success : function ( ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

Tips for minimizing the number of if statements in your code

Greetings! I am currently teaching myself the MEAN stack and have encountered a query related to minimizing the number of if checks in my code. The process involves users filling out their settings page, clicking enter, and then sending the data to the se ...

Is there a way to style the current page's link to make it appear disabled?

On my website, there are three main pages: Home, About, and Contact. I want the link to the current page to visually indicate that clicking on it would be redundant since the user is already on that page. Should I use CSS or jQuery for this task? And what ...

"Enhance your Handsontable experience with customizable dropdowns allowing for multiple

Seeking to enhance the functionality of the handsontable plugin by enabling multiple selections in its dropdown list. Tried extending the base Editor within the library following suggestions from this resource. Spent considerable time examining the source ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Discovering the final step of a for loop when working with JavaScript objects

Currently, my data consists of: {12: Object, 13: Object, 14: Object} I need help figuring out how to detect the final iteration in the for loop below: for (var i in objs){ console.log(objs[i]); } Does anyone have any solutions? ...

What is the process for calculating the total sum of dropdown list values?

Here is the JavaScript function I am using: <script type="text/javascript"> $(document).ready(function() { $('#roomOptions select').change(function() { var total = 0; $('#roomOptions select').each(function() ...

Ways to emphasize search outcomes in Flask/HTML?

I am currently working on creating a search box using HTML and the Flask framework in Python. Below is the layout I am working with: Layout My goal is to input text into the search box and have it highlighted within the text area on the same HTML page. F ...

Using JavaScript to open a window in ASPX page

When I use the code below to open a new window and receive a success message, I also want to close the current window. However, I am encountering an error: Error: newwindow is not defined var value = getQueryStrings(); var cust_id = value["cust_id ...

Error: Trying to access a property that is not defined (reference to 'user')

import { createSlice } from '@reduxjs/toolkit'; export const userSlice = createSlice({ name: 'user', initialState: { user: null, }, // The `reducers` field allows us to define reducers and generate associated actions redu ...

Is it possible to overwrite bytearray values?

As I embark on my Python journey, I find myself at a pivotal point - my very first question on Stack Overflow! I've been delving into the realm of converting a string of hexadecimal numbers to a bytearray, performing an XOR operation on each byte, an ...

Adjusting the height of a vertical slider in Vuetify2 is not customizable

I've been trying to adjust the height of a vertical slider in vuetify2, but setting it to "800px" or using style="height:800px" doesn't seem to work as intended. Even though the box within my grid expands, the height of the slider remains unchan ...