简体   繁体   中英

Change Array Elements Only Three Times, Repeat

What is the best way to change each element of an array based on the length of the array?

For example:

User #1 input = "XYZVC"

Expected Output = "BLABL"

User #2 input = "XYZVCAD"

Expected Output = "BLABLAB"

I want B to replace index[0] , L to replace index[1] , and A to replace index[2] . The part I'm struggling with the most is also getting it to repeat if the user input is longer than 3.

My Attempts

I've attempted to split() the input into an array, shift() it and push() it into a new array without any luck.

I've pasted in my code below for even more detail:

import React from 'react'

class UserInput extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: ''
        };
    }

        handleChange = (event) => {
            this.setState({value: event.target.value})
        }

        handleSubmit = (event) => {
            alert('Your input has been submitted: ' + this.state.value)
            event.preventDefault()
        }

        badRobot = () => {
            //Check length of user input
            //Add B, L, A, matching the length of the user input
            //Store it within a new variable
            //Plug that into the bad robots output

            let checkedInput = this.state.value
            let checkedArray = checkedInput.split('')
            const newArr = checkedInput.shift()
        }

    render(){
        return(
            <div>
            <form onSubmit={this.handleSubmit}>
                <label>
                    <p>Say Something</p>
                    <input type="text" value={this.state.value} onChange={this.handleChange} />
                </label>
                <input type="submit" value="Submit" />
            </form>
            <div>
            <h3>Good Robot</h3>
            <p>I hear you saying {this.state.value}. Is that correct?</p>
            <h3>Bad Robot</h3>
            <p>.</p>
            <h3>Kanyebot 5000</h3>
            <p>I'm gonna let you finish but Beyonce is {this.state.value}.</p>
            </div>
            </div>
        )
    }
}

export default UserInput

UPDATE

As it turns out, there is a string function, padStart (works with padEnd too) that will do exactly that pretty easily :

 const input1 = "XYZVCAD" const input2 = "erkjguherkluagheruhg" function mask(str){ return ''.padStart(str.length, 'BLA'); } console.log(mask(input1)) console.log(mask(input2))


One way to achieve it is to use the repeat function and then cut out your string depending on the original string length :

 const input1 = "XYZVCAD" const input2 = "erkjguherkluagheruhg" function mask(str){ return 'BLA'.repeat(str.length / 3 + 1).substring(0, str.length) } console.log(mask(input1)) console.log(mask(input2))

The repeat function will repeat your string x times, as you will see in the docs linked above. Here, since your string is 3 characters long, we only need to repeat your string depending on the length of the original one, divided by 3. I am adding one since a division like 5/3 will be rounded to 1 , leading to BLA even though your string is longer.

The last step, substring , will simply cut your string to the exact same length as the original one.

Here is another way of achieving it, by splitting your string into an array, and giving it the correct letter by using the modulus operator :

 const input1 = "XYZVCAD" const input2 = "erkjguherkluagheruhg" function mask(str){ return str.split('').map((ch, index) => 'BLA'[index % 3]).join('') } console.log(mask(input1)) console.log(mask(input2))

This isn't code, but it's the approach I would take:

  • Split the input into a char array
  • For loop through it, with index starting at 0
  • If index + 1 MOD 3 = 0, set value to 'A' ( array[i+1]%3 === 0 )
  • If index + 1 MOD 2 = 0, set value to 'L'
  • Otherwise set value to 'B'
  • Return a string of the joined array items (array.join)

 var myString = "somestringofsomelength"; var replacementsArr=["B","L","A"]; function replacer(str){ repString=""; for(var i=0; i<str.length;i++){ repString+=replacementsArr[i % replacementsArr.length]; } return repString; } console.log(replacer(myString));

That's the way I would do it. It's using remainder division to partition the string from being 12345678 in index relative to replacementsArr to 12312312

You could change it straight away

const letters = ['B','L','A'];

handleChange = (event) => {
  const length = event.target.value.length;
  const letter = letters[length%3];
  this.setState({value: this.state.value+letter});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM