Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use