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

Viewed 29

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?

4 Answers

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",
    ")"
]

Similar to what trincot said, your if statement is incorrect. Your if statement is looking for the number 1. Your array has the string "1".

var arr = ['(', '1', 'AND', '2', ')', 'OR', '(', '3', 'AND', '4', ')']
        arr.find(element => {
            if (element === '1') {
                var elementIndex = arr.indexOf(element);
                arr[elementIndex] = "Name = Test";
                console.log(elementIndex)
            }
        })

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

const idx = arr.findIndex((el) => el === "1");
if (idx > -1) {
  arr[idx] = "Name = Test";
}
Related