Reputation: 53
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?
Thanks
Upvotes: 1
Views: 137
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
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