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.
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."
);
}
Output
The first non-repeated element is: 6
JavaScript Program to Find the First Non-Repeated Element in an Array
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:
Table of Content
- Using For Loop in JavaScript
- Using find() Method
- Using map() Method
- Using Array Filter Method: