Monday, September 23, 2024
Google search engine
HomeLanguagesJavascriptFind the OR and AND of Array elements using JavaScript

Find the OR and AND of Array elements using JavaScript

Given an array and the is task to find the OR and AND operations of the values of an Array using JavaScript

These are the following methods:

Approach 1: Using simple for loop

It uses a simple method to access the array elements by an index number and use the loop to find the OR and AND of values of an Array using JavaScript. 

Example 1: This example uses a simple method to find the OR of Array elements using JavaScript. 

Javascript




function OR(input) {
    if (toString.call(input) !== "[object Array]")
        return false;
 
    let total = Number(input[0]);
    for (let i = 1; i < input.length; i++) {
        if (isNaN(input[i])) {
            continue;
        }
 
        total |= Number(input[i]);
    }
    return total;
}
 
console.log(OR([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));


Output

15

Example 2: This example uses a simple method to find the AND of Array elements using JavaScript. 

Javascript




function AND(input) {
    if (toString.call(input) !== "[object Array]")
        return false;
 
    let total = Number(input[0]);
    for (let i = 1; i < input.length; i++) {
        if (isNaN(input[i])) {
            continue;
        }
 
        total &= Number(input[i]);
    }
    return total;
}
 
console.log(AND([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));


Output

0

Approach 2: Using reduce() method

The array reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. 

Syntax:

array.reduce( function( total, currentValue, currentIndex, arr ), initialValue )

Example 1: This example uses the array reduce() method to find the OR of values of an Array using JavaScript. 

Javascript




let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
 
function ORofArray(OR, num) {
    return OR | num;
}
 
console.log(arr.reduce(ORofArray));


Output

15

Example 2: This example uses the array reduce() method to find the AND of values of an Array using JavaScript. 

Javascript




let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
 
function ANDofArray(AND, num) {
    return AND & num;
}
 
console.log(arr.reduce(ANDofArray));


Output

0
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments