JavaScript Program to Find the First Non-Repeated Element in an Array
Last Updated :
28 Jun, 2024
Finding the first non-repeated element in an array refers to identifying the initial occurrence of an element that does not occur again elsewhere within the array, indicating uniqueness among the elements.
Examples:
Input: {-1, 2, -1, 3, 0}
Output: 2
Explanation: The first number that does not repeat is : 2
Input: {9, 4, 9, 6, 7, 4}
Output: 6
Explanation: The first number that does not repeat is : 6
We have common approaches to perform this:
Approach 1 : Using For Loop in JavaScript
In this approach, we are using a nested for loop, iterate through each element in an array. Compare it with every other element to find the first non-repeated element. If found, print it; otherwise, indicate that all elements are repeated.
Syntax:
for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
}
Example: Below is the implementation of the above approach using nesting For loop.
JavaScript
let arr = [9, 4, 9, 6, 7, 4];
let n = arr.length;
let nonRepeatedFound = false;
for (let i = 0; i < n; i++) {
let j;
for (j = 0; j < n; j++) {
if (i != j && arr[i] == arr[j]) {
break;
}
}
if (j == n) {
console.log(
"The first non-repeated element is:",
arr[i]
);
nonRepeatedFound = true;
break;
}
}
if (!nonRepeatedFound) {
console.log(
"All elements in the array are repeated."
);
}
OutputThe first non-repeated element is: 6
Approach 2: Using find() Method
In this approach, we use the find method, search for the first non-repeated element in an array. then we use a ternary operator to display either the element or a message indicating that all elements are repeated.
Syntax:
array.find(function(currentValue, index, arr),thisValue);
Example: Below is the implementation of the above approach using Find method.
JavaScript
let arr = [9, 4, 9, 6, 7, 4];
let nonRepeated = arr.find(
(num) =>
arr.indexOf(num) === arr.lastIndexOf(num)
);
let result =
nonRepeated !== undefined
? "The first non-repeated element is: " +
nonRepeated
: "All elements in the array are repeated.";
console.log(result);
OutputThe first non-repeated element is: 6
Approach 3: Using map() Method
In this approach, map() method is used to iterate through an array, updating the count of each element using a Map, and then finding the first non-repeated element from the modified data.
Syntax:
map((element, index, array) => { /* … */ })
Example: In this example, The nonRepeatedElement function uses a Map to count element occurrences in an array using map(). It then finds and returns the first non-repeated element from the original array, or null if none.
JavaScript
function nonRepeatedElement(arr) {
/* Create a map to store
the count of each element */
const elementCount = new Map();
/* Use map to count the occurrences
of each element in the array */
arr.map((element) =>
elementCount.has(element)
? elementCount.set(
element,
elementCount.get(element) + 1
)
: elementCount.set(element, 1)
);
/* Iterate through the array again
to find the first non-repeated element */
for (let i = 0; i < arr.length; i++) {
if (elementCount.get(arr[i]) === 1) {
return arr[i];
}
}
/* If no non-repeated element is
found, return null or a default value */
return null;
}
const array = [9, 4, 9, 6, 7, 4];
const result = nonRepeatedElement(array);
console.log(result);
Approach 4: Using Array Filter Method:
The approach filters elements by comparing their first and last occurrences in the array. Elements with different first and last indexes are returned, ensuring only non-repeated elements are included.
Syntax:
array.filter(callback(element, index, arr), thisValue)
Example: In this example we finds the first non-repeated element in an array. If found, it prints the element; otherwise, it indicates that all elements are repeated.
JavaScript
let arr = [9, 4, 9, 6, 7, 4];
let nonRepeated = arr.filter((num) =>
arr.indexOf(num) === arr.lastIndexOf(num)
)[0];
let result = nonRepeated !== undefined
? "The first non-repeated element is: " + nonRepeated
: "All elements in the array are repeated.";
console.log(result);
OutputThe first non-repeated element is: 6
Approach 5: Using a Frequency Object
In this approach, we use an object to count the occurrences of each element in the array. This involves two main steps: first, creating a frequency object to count how many times each element appears in the array, and second, iterating through the array a second time to find the first element with a count of 1.
JavaScript
function firstNonRepeatedElement(arr) {
const frequency = {};
// Step 1: Build frequency object
for (const element of arr) {
frequency[element] = (frequency[element] || 0) + 1;
}
// Step 2: Find the first non-repeated element
for (const element of arr) {
if (frequency[element] === 1) {
return element;
}
}
return null; // All elements are repeated
}
// Example usage:
const arr1 = [-1, 2, -1, 3, 0];
console.log(firstNonRepeatedElement(arr1)); // Output: 2
const arr2 = [9, 4, 9, 6, 7, 4];
console.log(firstNonRepeatedElement(arr2)); // Output: 6
Similar Reads
JavaScript Program for the Minimum Index of a Repeating Element in an Array Given an array of integers arr[], The task is to find the index of the first repeating element in it i.e. the element that occurs more than once and whose index of the first occurrence is the smallest. In this article, we will find the minimum index of a repeating element in an array in JavaScript.E
5 min read
JavaScript Program to Find the First Repeated Word in String Given a string, our task is to find the 1st repeated word in a string. Examples: Input: âRavi had been saying that he had been thereâOutput: hadInput: âRavi had been saying thatâOutput: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUs
4 min read
JavaScript Program to Find Kâth Non-Repeating Character in String The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps
6 min read
JavaScript Program to Check if an Array Contains only Unique Values In this article, we are given an array, Our task is to find whether the elements in an array are unique or not.Examples:Input 1: 7,8,1,5,9 Output: true Input2: 7,8,1,5,5 Output: falseIn Input 1, elements 7,8,1,5,9 are distinct from each other and they were unique, there was no repetition of elements
4 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program to Print the kth Element in the Array We need to print the element at the kth position in the given array. So we start the program by taking input from the user about the size of an array and then all the elements of that array. Now by entering the position k at which you want to print the element from the array, the program will print
2 min read
Javascript Program for Last duplicate element in a sorted array We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7}Output :Last index: 4Last duplicate item: 6Input :
3 min read
JavaScript Program to Print All Distinct Elements in an Integer Array Given an Array of Integers consisting of n elements with repeated elements, the task is to print all the distinct elements of the array using JavaScript. We can get the distinct elements by creating a set from the integer array. Examples: Input : arr = [ 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9 ] Outpu
3 min read
Java Program to Remove Duplicate Elements From the Array Given an array, the task is to remove the duplicate elements from an array. The simplest method to remove duplicates from an array is using a Set, which automatically eliminates duplicates. This method can be used even if the array is not sorted.Example:Java// Java Program to Remove Duplicate // Ele
6 min read
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 : 3Explanation: The i
3 min read