jeebee
jeebee

Reputation: 53

Dynamically changing a Javascript map statement

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

Upvotes: 1

Views: 137

Answers (2)

jeebee
jeebee

Reputation: 53

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;}
 }

Upvotes: 0

KooiInc
KooiInc

Reputation: 122956

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.

Upvotes: 3

Related Questions