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

Lennart
  • 67
  • 1
  • 10
  • 1
    [Find the index](https://stackoverflow.com/questions/7346827/how-to-find-the-array-index-with-a-value) then change it. Or use a simple loop. – VLAZ May 11 '20 at 09:27

2 Answers2

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)
})
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • 1
    OP wants the array element in the original replaced. This code creates a new array. – Karthick May 11 '20 at 09:35
  • 1
    @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 – Vivek Doshi May 11 '20 at 09:36
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))
Iso
  • 3,148
  • 23
  • 31
Rob Bailey
  • 920
  • 1
  • 8
  • 23