I want to write a function to join an array to another but different way :
var myNumbers = [10,20,3,4,2]
var myOperations = ['+','-','*','/']
I want the operators locate between myNumbers element : 10+20-3*4/2 = 54
thank you
I want to write a function to join an array to another but different way :
var myNumbers = [10,20,3,4,2]
var myOperations = ['+','-','*','/']
I want the operators locate between myNumbers element : 10+20-3*4/2 = 54
thank you
Just Change the var str = 0 to str = ''
var myNumbers = [10,20,3,4,2]
var myOperations = ['+','-','*','/'];
var str = '';
for(var i = 0 ; i < myNumbers.length ; i++){
if(myOperations[i]){
str += myNumbers[i] + myOperations[i];
}else{
str += myNumbers[i];
}
}
console.log(str);
Some duplicates questions have already been pointed by other members and they could have helped you. Please find below a solution that I worked out for your problem.
var numbersAndOperations = myNumbers.map((a, i) => myOperations[i] ? [a, myOperations[i]] : [a])
/* this makes a 2 levels deep array from your 2 and avoids any undefined values through a ternary operator.
If you don't know ternary operators they are a shorthand for an if condition.
[[10, "+"], [20, "-"], [3, "*"], [4, "/"], [2]] */
const myMathString = numbersAndOperations.flat(2).join(',').replace(/,/g, '')
// this turns it into a string and remove the comas: "10+20-3*4/2"
function mathEval(mathString) { // this hack evaluates your math function and immediately returns a result.
return new Function('return ' + mathString)();
}
console.log(mathEval(myMathString)); // 24. The result is actually 24 because * and / are evaluated before the + and -
Hope that it helps :)