1

I want to evaluate a dynamically created string inside a map function. This is how it should work:

ar arr = [1,2,3,4,5];
var arr2 = arr.map(v=>((v+5)*6));     //Gives  [36, 42, 48, 54, 60]

I have created a string as below:

var s = '((v+5)*6)';
var arr2 = arr.map(v=>eval(s));      // I need something like this to work!

Can you do two things please?

  1. Show how this can be done using eval on the string I have created (or an amended string).
  2. Suggest another (better) method of doing this - I'm sure there is one.
  3. Don't just skip out point 1)

Thanks

6
  • 4
    why not take a function istead of a astring? Commented Dec 25, 2020 at 10:26
  • Could you add some more context as to why eval is necessary? Commented Dec 25, 2020 at 10:36
  • Is there a reason why you need to use eval? Even if you’re relying on user input that’s never a good idea. Commented Dec 25, 2020 at 10:37
  • The map statement is dynamically created. So the input could be something like this: var cmds = [ [ [ '+', '5' ], [ '*', '6' ] ] ]; I can code the input to form any string. I chose to try a method which took the array above and produces the string: "((v+5)*6))". Commented Dec 25, 2020 at 10:39
  • 1
    Point1: Your eval solution still works. Point2: You should provide more context to get help. Commented Dec 25, 2020 at 10:46

2 Answers 2

3

Notwithstanding the fact that eval probably is the wrong way to implement, this would be the way to make it run.

const arr = [1,2,3,4,5];
let s = '((v+5)*6)';
const arr2 = arr.map(eval(`v => ${s}`));
console.log(arr2);

Otherwise you should use or create a parser for the string, like Math.js. Or check this page for ideas.

Sign up to request clarification or add additional context in comments.

4 Comments

I made a booboo. Eval is disabled in the environment I am using. So my code would have worked - explains why I was so confused. Thanks for your help and all others who contributed. I will look at one of the other methods you suggested.
;) I'd say it is disabled for a reason. Hope the links in my answer can help then.
I can't use the math library. Is there no easier way to do this than to write my own maths expression parser?
The order of operations should follow the brackets I have added from inner to outer.
0

arr.map(v=>calc(v))

Pass something like this to the map function:

function calc(v){
          if (a=='plus') {return v+n;}
          if (a=='minus') {return v-n;}
          if (a=='multiply') {return v*n;}
          if (a=='divide') {return v/n;}
          if (a=='modulo') {return v%n;}
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.