How to find Index of element from array when array contains number and Brackets in string format

I have an array
var arr = ['(', '1', 'AND', '2', ')', 'OR', '(', '3', 'AND', '4', ')']

First I want to find if my array contains a element if have that element then replace it with another string.

I have tried following

arr.find(element=>{
  if(element == 1){
  var elementIndex = arr.indexOf(1);
  arr[elementIndex] = "Name = Test";
}
})

Here I’m searching for "1" in array. But always give me output as -1.

what I am doing wrong?

>Solution :

You should use the map array function as so:

var arr = ['(', '1', 'AND', '2', ')', 'OR', '(', '3', 'AND', '4', ')'];

var newArray = arr.map(el => el === '1' ? 'new_value' : el);

will output:

[
    "(",
    "new_value",
    "AND",
    "2",
    ")",
    "OR",
    "(",
    "3",
    "AND",
    "4",
    ")"
]

Leave a Reply