Bex
Bex

Reputation: 2925

Logical OR of arrays in javascript

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?

Upvotes: 2

Views: 420

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386654

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

Upvotes: 3

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

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

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370809

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

Upvotes: 1

Related Questions