Open In App

JavaScript Program to Find the First Non-Repeated Element in an Array

Last Updated : 26 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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."
    );
}

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

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

Output
6

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

Output
The first non-repeated element is: 6


Similar Reads

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: had Input: “Ravi had been saying that” Output: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUsing indexOf methodUsing Nested for loopUsing a
3 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 word frequencies, and identify the word with the
3 min read
JavaScript Program to Find Index of First Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the first occurrence of a number in a sorted array. We have the following methods to get the first occurrence of a given number in the sorted array. Methods to Find the Index of the First Occurrence of the element in the sorted arrayTable of Content Methods to Find the Index of the First Oc
5 min read
JavaScript Program to Check for Repeated Characters in a String
In this article, we are going to see various methods with which you can detect repeated characters in a string. Checking for repeated characters in a string involves examining the string's content to identify if any character occurs more than once. This helps detect duplications or repetitions within the text. Input: Str = “geeksforgeeks”Output:e,
5 min read
How to count number of occurrences of repeated names in an array of objects in JavaScript ?
Given an array of objects and the task is to find the occurrences of a given key according to its value. Example: Input : arr = [ { employeeName: "Ram", employeeId: 23 }, { employeeName: "Shyam", employeeId: 24 }, { employeeName: "Ram", employeeId: 21 }, { employeeName: "Ram", employeeId: 25 }, { employeeName: "Kisan", employeeId: 22 }, { employeeN
2 min read
JavaScript TypeError - Can't delete non-configurable array element
This JavaScript exception can't delete non-configurable array element that occurs if there is an attempt to short array-length, and any one of the array's elements is non-configurable. Message: TypeError: can't delete non-configurable array element (Firefox) TypeError: Cannot delete property '2' of [object Array] (Chrome) Error Type: TypeError Caus
1 min read
How to merge the first index of an array with the first index of second array?
The task is to merge the first index of an array with the first index of another array. Suppose, an array is array1 = {a, b, c} and another array is array2 = {c, d, e} if we perform the task on these arrays then the output will be result array { [0]=&gt; array(2) { [0]=&gt; string(1) "a" [1]=&gt; string(1) "c" } [1]=&gt; array(2) { [0]=&gt; string(
2 min read
How to get the first non-null/undefined argument in JavaScript ?
There are many occasions when we get to find out the first non-null or non-undefined argument passed to a function. This is known as coalescing. Approach 1: We can implement coalescing in pre-ES6 JavaScript by looping through the arguments and checking which of the arguments is equal to NULL. We then return the argument that is not NULL immediately
5 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 identify the K'th non-repeating character in the
4 min read
Delete the first element of array without using shift() method in JavaScript
Given an array containing some array elements and the task is to remove the first element from the array and thus reduce the size by 1. We are going to perform shift() method operation without actually using it with the help of JavaScript. There are two approaches that are discussed below: Using splice() MethodUsing filter() MethodMethod 1: Using s
1 min read