Categories: JavaScript

How to Find the Odd Number in an Array with JavaScript

In this post, we’ll look at how to use JavaScript to locate a missing positive odd number in an array. When one number is missing from a series of positively odd numbers that are consecutive, this can be helpful. To make the process easier for you to grasp, we’ll give you a step-by-step manual.

For Loop Method – Odd Number in an Array

Step 1: Create a function

To begin, let’s create a JavaScript function called findMissingOddNumber. This function will take an array of numbers as input and return the missing positive odd number.

function findMissingOddNumber(numbers) {
  // Code goes here
}

Step 2: Initialize variables

We’ll initialise two variables within the function: minNumber and maxNumber. The minNumber function returns the smallest number in the specified array, whereas the maxNumber function returns the largest number.

function findMissingOddNumber(numbers) {
  let minNumber = Math.min(...numbers);
  let maxNumber = Math.max(...numbers);
  // Code goes here
}

Step 3: Find the missing number

The missing odd number will then be found by iterating through the range of numbers from minNumber to maxNumber. To do this, a for loop will be used.

function findMissingOddNumber(numbers) {
  let minNumber = Math.min(...numbers);
  let maxNumber = Math.max(...numbers);

  for (let i = minNumber; i <= maxNumber; i++) {
    // Check if the current number is odd and not present in the array
    if (i % 2 !== 0 && !numbers.includes(i)) {
      return i;
    }
  }

  return -1; // If no missing odd number is found
}

Step 4: Testing the function

Now, let’s test our function with a sample array to see if it correctly identifies the missing odd number.

let numbers = [1, 3, 5, 7, 9, 13, 15, 17];
console.log(findMissingOddNumber(numbers)); // Output: 11

Other Methods – Odd Number in an Array

Array filter() Method

We can use the Array filter() method to locate the odd integers in an array by feeding it a callback that returns true when the number is odd and false otherwise.

function findMissingOddNumber(numbers) {
  let minNumber = Math.min(...numbers);
  let maxNumber = Math.max(...numbers);

  // Filter out the existing odd numbers in the array
  let existingNumbers = numbers.filter(num => num % 2 !== 0);

  // Find the missing odd number between minNumber and maxNumber
  let missingNumber = Array.from({ length: maxNumber - minNumber + 1 }, (_, index) => minNumber + index)
    .filter(num => num % 2 !== 0)
    .filter(num => !existingNumbers.includes(num));

  return missingNumber[0];
}

console.log(findMissingOddNumber(numbers)); // Output: 11

In this method, we first use numbers to filter the original array’s existing odd numbers away.(num => num% 2!== 0) is a filter. By doing this, an array called existingNumbers is created and it contains all of the odd numbers that were in the initial array.

Then, using the Array.from() and filter() methods, a new array is created. The odd numbers are filtered out of an array of numbers between minNumber and maxNumber (inclusive). Then, this array is further filtered to get rid of the numbers that are already in the existingNumbers array.

The missing odd number, which is kept in the missingNumber array, is then returned.

Array ForEach Method

function findMissingOddNumber(numbers) {
  let minNumber = Math.min(...numbers);
  let maxNumber = Math.max(...numbers);
  let missingNumber = -1;

  // Iterate over the range of numbers
  Array.from({ length: maxNumber - minNumber + 1 }, (_, index) => minNumber + index)
    .forEach(num => {
      if (num % 2 !== 0 && !numbers.includes(num)) {
        missingNumber = num;
      }
    });

  return missingNumber;
}

console.log(findMissingOddNumber(numbers)); // Output: 11

In this code, we first determine the minimum (minNumber) and maximum (maxNumber) values from the given array using the Math.min() and Math.max() functions, respectively.

Next, we use the Array.from() method along with the forEach() method to iterate over the range of numbers between minNumber and maxNumber. We create an array of these numbers using Array.from() and iterate over each number using forEach(). Within the iteration, we check if the number is odd and if it is not included in the original array (!numbers.includes(num)). If both conditions are true, we update the missingNumber variable with the current number.

Finally, we return the value of the missingNumber variable, which will contain the missing positive odd number if found. If no missing number is found, the function will return -1.

Related Articles

JavaScript Interview Questions and Answers

Node.js Interview Questions and Answers

How to avoid confusion between ReactJS and React Native

Password Strength Checker Using JavaScript

How To Efficiently Remove Items From An Array In JavaScript

Conclusion

In this post, we looked at various JavaScript techniques for locating a missing positive odd number in an array. Three methods were discussed: Array.filter(), Array.forEach(), and a prior example utilising a for loop. The choice is based on preferences and unique needs, but each approach offers a workable solution.

Developer Diary

Share
Published by
Developer Diary

Recent Posts

Git Tag Cheat Sheet

Introduction Git tags are an essential feature of version control systems, offering a simple way…

4 months ago

Understanding Web Storage: Cookies, Local Storage

Introduction The methods that browsers employ to store data on a user's device are referred…

4 months ago

Setting up OpenVPN Access Server in Amazon VPC – AWS

Introduction A well-known open-source VPN technology, OpenVPN provides strong protection for both people and businesses.…

4 months ago

Enhance Error Tracking & Monitoring: Integrate Sentry with Node.js & Express.js

Introduction Integrating Sentry into a Node.js, Express.js, and MongoDB backend project significantly enhances error tracking…

4 months ago

Comparing Callbacks, Promises, and Async/Await in JavaScript

Introduction In the world of JavaScript development, efficiently managing asynchronous operations is essential. Asynchronous programming…

6 months ago

How To Secure Nginx with Let’s Encrypt on Ubuntu EC2 Instance

Introduction Let's Encrypt is a Certificate Authority (CA) that makes it simple to obtain and…

8 months ago