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.
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
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:
Contact Us