Open In App

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:

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.




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

Output
[ 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 (^).

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



Article Tags :