- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding unlike number in an array - JavaScript
We are required to write a JavaScript function that takes in an array of literals containing all similar elements but one. Our function should return the unlike number.
Example
Following is the code −
const arr = [2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]; // considering that the length of array is atleast 3 const findUnlike = arr => { for(let i = 1; i < arr.length-1; i++){ if(arr[i] - arr[i-1] !== 0 && arr[i]-arr[i+1] === 0){ return arr[i-1]; }else if(arr[i] - arr[i-1] !== 0 && arr[i]-arr[i+1] === 0){ return arr[i] }else if(arr[i] - arr[i-1] === 0 && arr[i]-arr[i+1] !== 0){ return arr[i+1]; }; continue; }; };
Output
Following is the output in the console −
2
Advertisements