Discovering the anomaly within a set of values

I developed a function that can identify the outlier in an array consisting of a set of odd numbers and one even number, or vice versa. For example, findOutlier([2,6,8,10,3]) will return 3 as it is the only odd number in the array.

Although I have successfully implemented this function, I encountered an issue with handling certain large negative numbers. It seems to return undefined instead of the expected outlier number.

Below is the code snippet:

function findOutlier(integers){
  let testingForOdds = true;
  let evenCounter = 0;
  let oddCounter = 0;
  for (let i = 0; i < 3; i++){
    if (integers[i] % 2 === 0){
      evenCounter = evenCounter + 1
      if (evenCounter === 2){
        testingForOdds = true;
      }
    }
    else if (integers[i] % 2 === 1){
      oddCounter = oddCounter + 1
      if (oddCounter === 2){
        testingForOdds = false;
      }
    }
  }
  if (testingForOdds){
    for (let i = 0; i < integers.length; i++){
      if (integers[i] % 2 === 1){
        return integers[i]
      }
    }
  } else {
    for (let i = 0; i < integers.length; i++){
      if (integers[i] % 2 === 0){
        return integers[i]
      }
    }
  }
}
findOutlier([-100000000007, 2602, 36]);

Despite working flawlessly on examples like findOutlier([2,6,8,10,3]), the function shows unexpected behavior with negative values such as in

findOutlier([-100000000007, 2602, 36]);
. Instead of returning the correct result, it returns undefined. What could be causing this discrepancy?

Answer №1

As pointed out by Michael, the problem occurs because -100000000007 % 2 results in -1. It's worth mentioning that you have the opportunity to enhance your code efficiency by reducing the number of comparisons made in this way:

function findOutlier(arr) {
  let isEven = true;
  const a = arr[0];
  const b = arr[1];
  if (([-1, 1].includes(a % 2) && [-1, 1].includes(b % 2))) {
    isEven = false;
  } else if (!(a % 2 === 0 && b % 2 === 0)) {
    const c = arr[2];
    if (c % 2 === 1) isEven = false;
  }
  for (let i = 0; i < arr.length; i += 1) {
    const even = arr[i] % 2 === 0;
    if (even !== isEven) return arr[i];
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am struggling to make my button hover effects to function properly despite trying out numerous suggestions to fix it

As a newcomer, this is my first real assignment. I've managed to tackle other challenges successfully, but this one seems a bit more complex and I'm struggling to pinpoint where I'm going wrong. Despite googling various solutions, none of th ...

Is it possible to manipulate the carousel image within the div element?

I am working on a Bootstrap code snippet that showcases an image using the w-100 class to span the full width of the page. However, the challenge I'm facing is making sure the image is visible to users while keeping it small enough so they won't ...

Is there a requirement to download and set up any software in order to utilize Highchart?

I've been working on a project to create a program that displays highcharts, but all I'm getting is a blank page. Here's my code: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charse ...

Error in String.Format function: Index (zero based) needs to be a non-negative number and smaller than the total elements in the argument list

I am attempting to modify the formatting of a string by utilizing an array of values: Dim arguments(2) As Object arguments(0) = "some text" arguments(1) = "more text" arguments(2) = "and other text" Test(arguments) The function Test is outlined below: ...

Retrieving a specific field from an object within an array

Struggling with Meteor and MongoDB, I am having trouble accessing a specific field from objects within an object array. Details of my documents: { "_id" : "p6c4cSTb3cHWaJqpG", "createdAt" : ISODate("2016-05-11T11:30:11.820Z"), "username" ...

The addition of meshes in real-time leads to a decrease in control responsiveness

I'm currently working on creating a 3D map using Three.js. My process involves building the geometry and texture with images of size 256x256 pixels, then constructing a THREE.Mesh to add to the scene upon completion. However, I've noticed that ...

The SetTimeOut function is ineffective for resetting the colour of every cell in a table

I am facing an issue with two HTML tables. The cell values in both tables are changing every 3 seconds and the background color of each cell is set based on the value from the previous cycle. Additionally, a setTimeout function is used to reset the backgro ...

Tips for Implementing CdvPurchase.Store in Angular

Is there a way to configure cordova-plugin-purchase v13 in conjunction with Angular 15? Here is a snippet of what I have attempted. Below is my PaymentService class that is set to be provided at the root level. // payment.service.ts import { Injectable } ...

What are the steps to clipping a canvas using CSS clip-path?

When it comes to clipping a canvas, there are multiple methods that can be used. One way is to create a path with getContext('2d') and set globalCompositeOperation. Another method involves using -webkit-clip-path or clip-path, though the latter m ...

What causes React useEffect dependency to be seemingly overlooked?

My React component contains two useEffect hooks. One of these should only run when a value stored in context is updated. However, I'm noticing that this hook runs even before the context value changes, and I can't figure out why. Below are the c ...

Obtain the Ajax function to provide a result of either true or false

I'm struggling to make an Ajax function return a true or false value for validation purposes. The other function needs to receive this value to determine the next steps. I'm certain I've accomplished this before, but for some reason, it&apo ...

Error: Unable to find the definition for Image (Next.js)

This new component in my next js project allows me to write a quote on an image and display it on the canvas. However, I am encountering an issue with the Image() function in JavaScript which typically runs on the browser. It seems that Next.js first execu ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

Assign the ng-repeat item to a variable in the controller's scope

Can anyone help me figure out how to pass a particular item from my view to a function in my controller? Here is the code: The view where I want to pass p.id <tr ng-repeat=" p in projetsListe"> <td>{{p.NomProjet}}</td> <td>{{c ...

Numerous textareas fail to function properly according to JQuery's standards

Need help with resizing multiple textarea elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea, but it does not work when there are multiple textareas on the page. Here is the c ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Delete a character from a string in JavaScript by targeting a specific position starting from the end

I've been grappling with a problem involving removing a specific character at a known position from the back of a string. Here's the situation: Currently, I have strings like: 'RX8567' 'A8532' '18256' I want to de ...

Exploring the Power of D3.js: Loading and Visualizing Multiple Networks using JSON Files and the Force

I have a collection of networks consisting of nodes and links stored in various JSON files. I am using D3.js to load them into a Force Layout, where they each load and layout perfectly when loaded individually. However, I would like to enhance the function ...

How can one efficiently locate the suitable dynamic path resource within an array of resources?

In my scenario, I am dealing with an Array of resources that includes a dynamic resource like "guides/:guideId/packages" and a currentURL (guides/GUIDE007/packages): const resources = ["guides", "guides/files", "guides/:guideId/packages"]; const currentURL ...

Show or hide a div through two variables that toggle between different states

It's possible that I'm not fully awake, so missing the obvious is a possibility. However, I have 2 variables that determine whether a div has a specific class or not. The class functions more like a toggle; so the following conditions should tri ...