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, 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:
- Using array filter() and indexOf() Methods
- Using array forEach() Loop with XOR Operator
JavaScript Program to Find Element that Appears once in Array using array filter() and indexOf() Methods
The first approach to solve the problem is to use the filter() method of arrays. It will return a new array say uniqueArr. Now perform the filter() method on the input array and check if the index of the current element in the array is equal to the last index of the element in the array. Because if they are equal then the element is unique. Print the first element of uniqueArr array.
Example: This example implements array filter() and indexOf() methods to get the element.
Javascript
const arr = [ 5, 9, 2, 7, 4, 6, 8, 1, 5, 1, 4, 6, 3, 7, 8, 2, 9 ]; const uniqueArr = arr.filter((num) => { return arr.indexOf(num) === arr.lastIndexOf(num); }); console.log(uniqueArr); |
[ 3 ]
JavaScript Program to Find Element that Appears once in Array using forEach() Loop with XOR Operator
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
Javascript
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); |
3