
- 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
Finding the first redundant element in an array - JavaScript
Let’s say, 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).
Therefore, 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
Following is the code −
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
This will produce the following output in console −
1
- Related Articles
- Finding first unique element in sorted array in JavaScript
- Finding the first unique element in a sorted array in JavaScript
- Finding the majority element of an array JavaScript
- Finding the first non-consecutive number in an array in JavaScript
- Finding missing element in an array of numbers in JavaScript
- Finding the index of first element in the array in C#
- Get the first element of array in JavaScript
- Removing redundant elements from array altogether - JavaScript
- Constructing an array of addition/subtractions relative to first array element in JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript
- First element and last element in a JavaScript array?
- Finding the index of the first element that violates the series (first non-consecutive number) in JavaScript
- Finding the longest string in an array in JavaScript
- Finding unlike number in an array - JavaScript

Advertisements