-9

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

Hamid Mohamadi
  • 141
  • 2
  • 4
  • 1
    Welcome to Stack Overflow ! Please read the [tour], [help] and [ask]. Users are expected to show their attempts or research in their question, to ensure a better reception. – Pac0 Sep 18 '19 at 08:11
  • 2
    Also, `10+20-3*4/2` is 24 – TheMaster Sep 18 '19 at 08:15

2 Answers2

0

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);
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
0

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 :)

GBouffard
  • 1,125
  • 4
  • 11
  • 24