
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Detecting the first non-unique element in array in JavaScript
We are required to write a function that returns the index of the very first element that appears at least twice in the array. If no element appears more than once, we have to return -1. We have to do this in constant space (i.e., without utilizing extra memory).
So, let's write the solution for this problem.
We will use a for loop to iterate over the array and use the Array.prototype.lastIndexOf() method to check for duplicacy.
Example
The code for this will be −
const arr1 = [0, 1, 1, 2, 3, 4, 4, 5]; const firstRedundant = arr => { for(let i = 0; i < arr.length; i++){ if(arr.lastIndexOf(arr[i]) !== i){ return i; }; }; return -1; } console.log(firstRedundant(arr1)); // 1
Output
The output in the console will be −
1
- Related Articles
- Detecting the first non-repeating string in Array in JavaScript
- Finding first unique element in sorted array in JavaScript
- Finding the first unique element in a sorted array in JavaScript
- Detecting the largest element in an array of Numbers (nested) in JavaScript
- JavaScript Find the first non-consecutive number in Array
- Get the first element of array in JavaScript
- First element and last element in a JavaScript array?
- Finding the first non-consecutive number in an array in JavaScript
- Finding the first redundant element in an array - JavaScript
- Finding the index of the first element that violates the series (first non-consecutive number) in JavaScript
- Making array unique in JavaScript
- JavaScript: How to filter out Non-Unique Values from an Array?
- Constructing an array of addition/subtractions relative to first array element in JavaScript
- Number of non-unique characters in a string in JavaScript
- How to remove first array element in JavaScript and return it?

Advertisements