Home > Net >  How to change the value or a string inside the array
How to change the value or a string inside the array

Time:10-05

I want to find the exact value of what is giving the API which is b string and modify the value of it

const arr = ["a","b","c","d","e"]

For example I want to modify the "b" string to "d" string. But the API is giving a limited string and I want to find if there's a 'b' string then modify it

CodePudding user response:

I might be misunderstanding, but can you not just do :

arr[1]=arr[3]

Because arr then becomes: ['a', 'd', 'c', 'd', 'e']. If you want to first error check that arr has a value at 'd' (ie arr.length !< 4), you could do: arr[1]= arr.length > 3 ? arr[3] :arr[1].

CodePudding user response:

you have to use your custom function. when ever APIcall completed you have to check if there is "b" inside array just get the index and change it to "d"

var index = arraysOfElementFromBackend.indexOf("b");
if (index !== -1) {
    arraysOfElementFromBackend[index] = "d";
}

CodePudding user response:

With the limited information given, I believe you want to do

const arr = ["a","b","c","d","e"];
const idx = arr.indexOf("b");
if (idx !== -1) arr[idx]="d";
console.log(arr);

  • Related