How to use array filter() and indexOf() Methods In Javascript

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

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

Similar Reads

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....

Using forEach() Loop with XOR Operator

Another approach to solving the problem is to use the XOR operator (^)....

Using Map Data Structure

In this approach, we can utilize a JavaScript Map data structure to keep track of the count of each element in the array. Then, we iterate through the array, updating the count in the map. Finally, we iterate through the map and return the key whose value is 1, indicating that it appeared only once in the array....