Is there a way to get parenthesis from an array, and then put all the elements in them into an array

Tags:



Is it possible to take an array say:

["(",89,"+",8,")","*",92]

and get a new array with

["(",89,"+",8,")"]

I have tried to do stuff like

for (i=myarr.indexOf("(");i<myarr.indexOf(")");i++) {
  otherarr.push(i)
} 

It didn’t seem to work, and other solutions involve just messing around with that. I couldn’t seem to get it to work

Answer

Based on minimal criteria given you can use slice() with start index at the index of the ( and end index one past the ).

This is only based on the very simple case you have shown and does not consider any nested ()

const arr=["(",89,"+",8,")","*",92],
res = arr.slice(arr.indexOf('('), arr.indexOf(')') + 1 );

console.log(JSON.stringify(res))


Source: stackoverflow