How to use forEach() Loop with XOR Operator In Javascript
Another approach to solving the problem is to use the XOR operator (^).
- Initialize ans as 0.
- Now apply forEach loop in the array and for every element perform its XOR operation with ans and return ans.
- Since XOR is commutative and associative it will cancel out any duplicates in the array and only the unique element will be contained in ans.
- Print ans.
Example: This example uses Array filter and XOR operator to get required result
const arr = [
5, 9, 2, 7, 4, 6, 8, 1, 5,
1, 4, 6, 3, 7, 8, 2, 9
];
let ans = 0;
arr.forEach((num) => {
ans ^= num;
});
console.log(ans);
Output
3
JavaScript Program to Find Element that Appears once in Array where Other Elements Appears Twice
Given an Array of Integers consisting of n elements where each element appears twice except one element. The task is to find the element which appears only once in the input array in JavaScript.
Example:
Input : arr = [ 5, 9, 2, 7, 4, 8, 6, 1, 5, 1, 4, 6, 3, 7, 8, 2, 9 ]
Output : 3
Explanation: The input array consists of 17 elements
where all elements except 3 appears twice i.e.
(1, 2, 4, 5, 6, 7, 8, 9) are repeating twice. Hence
the answer will be 3.
Input : arr = [ 4, 7, 1, 4, 1 ]
Output : 7
Approaches to Find the Element that Appears Once in Array where Every Other Element Appears Twice:
Table of Content
- Using array filter() and indexOf() Methods
- Using forEach() Loop with XOR Operator
- Using Map Data Structure