0

I have two arrays like below,

var arr1 = [false, true, false];

var arr2 = [And, Or, null];

Now i make this two array with operator exchange.

And replace with && Or replace with ||

Is this possible to acheive?

Now I expected result is

var result = false && true || false;

if(result){
// when result true, 
}

else{
// when result false
}

Please suggest your answer!!!

Gokul Kumar
  • 389
  • 6
  • 16

2 Answers2

1

It will work only if arr1 and arr2 will satify these two condition

  1. arr2 should only two type's of value 'And' and 'Or'
  2. length of arr2 should be arr1.length-1

var arr1 = [false, true, false];

var arr2 = ['And', 'Or', null];

arr2 = arr2.map(val => {
    val = val == "And" ? "&&" : val;
    val = val == "Or" ? "||" : val;
    return val;
})


var resultantArray = arr1.reduce((obj, val, index) => {

    obj.push(val);
    if (arr2[index] && index < arr1.length - 1)
        obj.push(arr2[index]);
    return obj
}, []);

var resultantCondition = resultantArray.join(" ");
console.log(resultantCondition);

if (eval(resultantCondition))
    console.log(true);

else
    console.log(false);
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
  • Thanks for your update, But this output consider as a string. For example you can check the if condition, it returns always true. – Gokul Kumar May 31 '18 at 03:47
  • `it returns always true` means? With above sample It is going in false condition, If you use `var arr2 = ['Or', 'Or', null];` this array then you will get true. – Nishant Dixit May 31 '18 at 05:12
0

You could strings for the operands and an object for collecting all operators and reduce the array with the values by getting the function of the same index anf return the value of the function call.

var fn = { and: (a, b) => a && b, or: (a, b) => a && b, identity: a => a },
    operands = [false, true, false],
    operators = ['and', 'or', null],
    result = operands.reduce((a, b, i) => (fn[operators[i]] || fn.identity)(a, b));

console.log(result);    
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392