1

How can I rename an element of an array if this element contains a given string?

So e.g. I have an array in my state:

constructor(props) {
        super(props);
        this.state = {
            array: ["stack", "overflow", "question"],
        }
}

and now I wanna replace the string question with e.g. answer. So I could easily do this if the index of question is always the same but how can I replace question with answer if question always have an other index? This should be done in the most efficient way. Hope anyone can help me. Thanks

1
  • 1
    Find the index then change it. Or use a simple loop. Commented May 11, 2020 at 9:27

2 Answers 2

5

HERE YOU GO :

This is just a code snippet, you can apply your logic as well, I have just compare exact string for simplicity of code.

console.log(
        ["stack", "overflow", "question"]
        .map(str => str==="question" ? "answer" : str)
)


In react, you can use it like

this.setState((state) => {
    array : state.array.map(str => str==="question" ? "answer" : str)
})
Sign up to request clarification or add additional context in comments.

2 Comments

OP wants the array element in the original replaced. This code creates a new array.
@dww, in react you can't mutate state directly, you need new copy of that, so this is perfectly fine for react. as you can see the array is inside the state
1

You could use indexOf to find out what index the item is at and then replace that.

Something like:

const arr = ["stack", "overflow", "question"];

function replaceStr(newStr, str, arr){
  if(arr.indexOf(str) >= 0){
    arr[arr.indexOf(str)] = newStr;
  }
  return arr;
}

console.log(replaceStr("Hello", "question", arr))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.