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 −

 Live Demo

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

Updated on: 20-Apr-2021

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements