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 find the Index of Last Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the last occurrence of a number in a sorted array. We have the following methods to get the last occurrence of a given number in the sorted array. Methods to Find the Index of the Last Occurrence of the Target Element in the Sorted ArrayUsin
4 min read
JavaScript Program to Get a Non-Repeating Character From the Given String
In JavaScript, we can find the non-repeating character from the input string by identifying the characters that occur only once in the string. There are several approaches in JavaScript to get a non-repeating character from the given string which are as follows: Table of Content Using indexOf and la
3 min read
JavaScript Program to Remove Duplicate Elements From a Sorted Array
Given a sorted array arr[] of size N, the task is to remove the duplicate elements from the array. Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: arr[] = {2} Explanation: All the elements are 2, So only keep one instance of 2. Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5} Output: arr[] = {1, 2, 3, 4,
3 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
JavaScript Program to Find Second Most Repeated Word in a Sequence
Finding the second most repeated word in a sequence involves analyzing a given text or sequence of words to determine which word appears with the second-highest frequency. This task often arises in natural language processing and text analysis. To solve it, we need to parse the input sequence, count
5 min read
JavaScript Program to Check if Kth Index Elements are Unique
In this article, We have given a String list and a Kth index in which we have to check that each item in a list at that particular index should be unique. If they all are unique then we will print true in the console else we will print false in the console.Example:Input: test_list = [âgfgâ, âbestâ,
6 min read
JavaScript Program to Find Common Elements Between Two Sorted Arrays using Binary Search
Given two sorted arrays, our task is to find common elements in two sorted arrays then the program should return an array that contains all the elements that are common to the two arrays. The arrays can contain duplicate elements, that is, values at one index in an array can be equal to the values a
3 min read