2

I would like to perform a logical OR operation on arrays in javascript, so that performing this operation on arrays a and b

let a = [0,1,0]
let b = [0,0,5]

gives me

OR(a, b)
[0,1,5]

What would be an efficient and idiomatic way to implement OR?

0

3 Answers 3

3

You could reduce the wanted arrays by taking a mapping and an or function.

const or = (a, b) => a || b,
      mapped = fn => (a, b) => a.map((v, i) => fn(v, b[i]));

var a = [0, 1, 0],
    b = [0, 0, 5],
    c = [a, b].reduce(mapped(or));

console.log(c);

Sign up to request clarification or add additional context in comments.

Comments

2

Just use || operator in combination with map method by passing a callback function as argument.

let a = [0,1,0]
let b = [0,0,5]

let c = a.map((item, index) => item || b[index]);
console.log(c);

Comments

1

Assuming the arrays always have the same length, use .map and ||:

const OR = (a, b) => a.map((aItem, i) => aItem || b[i]);
let a = [0,1,0]
let b = [0,0,5]
console.log(
  OR(a, b)
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.