Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to calculate the XOR of array elements using JavaScript?
We will use a for loop to iterate through the array. We will initialize a variable called "result" with the value of the first element in the array. For each subsequent element in the array, we will use the XOR operator to update the value of "result" with that element. This process will continue until all elements in the array have been processed, resulting in the final XOR value of all elements in the array.
Let us first understand what XOR is. We will also see how XOR operation on an array works.
Understanding Array XOR
-
The XOR (exclusive or) operation is a bitwise operation that compares two binary digits and returns 1 if they are different and 0 if they are the same.
-
An XOR operation on an array is a way to combine the values of all elements in the array using the XOR operation.
-
In an array A of size n, the XOR of all elements can be calculated by using the following formula: A[0] ? A[1] ? A[2] ? ? ? A[n-1].
-
XORing all elements of array gives the number that occurs only once in array (when all other elements appear an even number of times).
-
An important application of XOR operation on arrays is in finding the single number in an array that occurs only once while all other elements occur twice.
XOR Properties
XOR has some useful properties that make it valuable for array operations:
-
Commutative: a ? b = b ? a
-
Associative: (a ? b) ? c = a ? (b ? c)
-
Self-inverse: a ? a = 0
-
Identity element: a ? 0 = a
Method 1: Using For Loop
Here is the basic approach to calculate XOR of all array elements using a for loop:
function calculateXOR(arr) {
let result = arr[0];
for (let i = 1; i < arr.length; i++) {
result = result ^ arr[i];
}
return result;
}
let testArray = [1, 2, 3, 4, 5];
let xorResult = calculateXOR(testArray);
console.log("XOR of [1, 2, 3, 4, 5]:", xorResult);
// Example with duplicate elements
let duplicateArray = [1, 2, 3, 2, 1];
let xorDuplicate = calculateXOR(duplicateArray);
console.log("XOR of [1, 2, 3, 2, 1]:", xorDuplicate);
XOR of [1, 2, 3, 4, 5]: 1 XOR of [1, 2, 3, 2, 1]: 3
Method 2: Using reduce() Method
A more functional approach using the reduce() method:
function calculateXORReduce(arr) {
return arr.reduce((result, current) => result ^ current, 0);
}
let numbers = [4, 2, 8, 4, 2];
let xorResult = calculateXORReduce(numbers);
console.log("XOR using reduce:", xorResult);
// Finding single number in array
let singleNumArray = [7, 3, 5, 4, 5, 3, 4];
let singleNumber = calculateXORReduce(singleNumArray);
console.log("Single number that appears once:", singleNumber);
XOR using reduce: 8 Single number that appears once: 7
Step-by-Step Example
Let's trace through how XOR works with array [1, 2, 3, 4, 5]:
function traceXOR(arr) {
console.log("Tracing XOR operation:");
let result = arr[0];
console.log(`Initial result: ${result}`);
for (let i = 1; i < arr.length; i++) {
console.log(`${result} ^ ${arr[i]} = ${result ^ arr[i]}`);
result = result ^ arr[i];
}
console.log(`Final XOR result: ${result}`);
return result;
}
traceXOR([1, 2, 3, 4, 5]);
Tracing XOR operation: Initial result: 1 1 ^ 2 = 3 3 ^ 3 = 0 0 ^ 4 = 4 4 ^ 5 = 1 Final XOR result: 1
Practical Use Case: Finding Unique Element
XOR is commonly used to find the unique element in an array where every other element appears exactly twice:
function findUniqueElement(arr) {
return arr.reduce((xor, num) => xor ^ num, 0);
}
// Every number appears twice except one
let uniqueArray = [2, 3, 5, 4, 5, 3, 4];
let unique = findUniqueElement(uniqueArray);
console.log("Array:", uniqueArray);
console.log("Unique element:", unique);
// Another example
let anotherArray = [1, 1, 2, 2, 3, 3, 4];
console.log("Unique in [1,1,2,2,3,3,4]:", findUniqueElement(anotherArray));
Array: [2, 3, 5, 4, 5, 3, 4] Unique element: 2 Unique in [1,1,2,2,3,3,4]: 4
Comparison of Methods
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| For Loop | Good | Fast | Traditional approach |
| reduce() | Excellent | Slightly slower | Functional programming |
Conclusion
XOR operation on arrays is useful for finding unique elements and solving various algorithmic problems. The reduce() method provides a cleaner syntax, while the for loop offers better performance for large arrays.
