- 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 array number that have no matching positive or negative number in the array using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers. For each number in the array there will also be its negative or positive compliment present in the array, but for exactly one number, there will be no compliment.
Our function should find and return that number from the array.
Example
Following is the code −
const arr = [1, -1, 2, -2, 3]; const findOddNumber = (arr = []) => { let count = 0; let number = arr.reduce((total, num) => { if (num >= 0) count++ else count-- return total + num; }, 0) return number / Math.abs(count); }; console.log(findOddNumber(arr));
Output
3
Advertisements