Create a JavaScript program that can identify which number in a given array is different from the other two when two of the numbers in the array are equal

function checkThirdNumber() {
    let num1 = parseInt(document.querySelectorAll('.checkThirdInput')[0].value);
    let num2 = parseInt(document.querySelectorAll('.checkThirdInput')[1].value);
    let num3 = parseInt(document.querySelectorAll('.checkThirdInput')[2].value);
    document.getElementById('checkThirdResult').innerHTML = findThirdNumber([num1, num2, num3]);
  }
  function findThirdNumber(numbers) {
    let twoEquals = [];
    let oneUnequal = [];
    for (var i = 0; i < numbers.length; i++) {
      for (var j = i + 1; j < numbers.length; j++) {
        if (numbers[i] == numbers[j])  {
          twoEquals.push(numbers[i]);      
        }
        if (numbers[i] != numbers[j]) {
          oneUnequal.push(numbers[i]);
        }
      }
    }
    if ((twoEquals.length == 2) && (oneUnequal.length == 1)) {
      return 'The two equal numbers are: ' + twoEquals + '<br>' + 'The third number is: ' + oneUnequal;
    } else {
      return 'Numbers do not match.'
    }  
  }
<input type="number" class="checkThirdInput" value="3">
<input type="number" class="checkThirdInput" value="3">
<input type="number" class="checkThirdInput" value="4">
<button onclick="checkThirdNumber()">Check</button>
<div id="checkThirdResult"></div>

I attempted to resolve the issue using the code above, but for some reason it is not functioning correctly. The algorithm checks for two matching numbers and one different number in the input array, but there are some errors in the implementation.

Answer №1

function identifyThirdDuplicate(arr) {
let unique = [];
let duplicates = [];
for (var i = 0; i <= arr.length - 1; i++) {
    let isUnique = true;
    for (var j = i + 1; j <= arr.length; j++) {
        if (arr[i] === arr[j]) {
            duplicates.push(arr[i]);
            isUnique = false;
            break;
        }
    }
    if (isUnique && duplicates.indexOf(arr[i]) < 0) {
        unique.push(arr[i]);
    }
}
if (duplicates.length == 1) {
    return 'The duplicate is: ' + duplicates[0] + '<br>' + 'The third unique element: ' + unique[0];
} else {
    return 'No duplicate found.';
}

}

Answer №2

You seem to be approaching this in a rather intricate manner.

Consider utilizing some predefined functions like map() and filter(). Additionally, instead of returning the htmlString from the function, you can directly assign it to the element's innerHTML.

Here is a suggested approach:

function findThird1() {
  let resultEl = document.getElementById('findThirdResult');
  let all = document.querySelectorAll('.findThirdInput');
  //retrieve all values
  let allValues = Array.from(all).map(el => el.value);
  //find the duplicates
  var two = allValues.filter((e, i, a) => a.indexOf(e) !== i);
  //find the unique value
  var one = allValues.filter(i => !two.includes(i));
  if (two.length && one.length) {
    resultEl.innerHTML =  'The duplicates are: ' + two + '<br>' + 'The unique value: ' + one;
  } else {
    resultEl.innerHTML = 'No duplicates found.'
  }  
}
<input type="number" class="findThirdInput" value="3">
<input type="number" class="findThirdInput" value="3">
<input type="number" class="findThirdInput" value="4">
<button onclick="findThird1()">Try</button>
<div id="findThirdResult"></div>

Answer №3

Have you considered trying a solution like this?

function checkEquality1() {
  let num1 = parseInt(document.querySelectorAll('.checkEqualityInput')[0].value);
  let num2 = parseInt(document.querySelectorAll('.checkEqualityInput')[1].value);
  let num3 = parseInt(document.querySelectorAll('.checkEqualityInput')[2].value);
  document.getElementById('checkEqualityResult').innerHTML = checkEquality2([num1, num2, num3]);
}

function checkEquality2(arr) {
  let flag = false;
  for (var i = 0; i < arr.length - 1; i++) {
    if (arr[i] === arr[i + 1]) {
      flag = true;
      break;
    }
  }
  return flag ? 'Equals' : 'Not Equals';
}

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

Obtaining the current value with each keystroke

While working with vue.js, I'm building a table that contains an input field called quantity. However, when I start typing the first word, it shows 'empty' on the console. If I type 3, it displays empty; and if I type 44, it prints 4. I am ...

What is the method for selecting the element currently under the mouse cursor?

Is it possible to change the color of all elements you hover over using plain Javascript without jQuery? HTML <ul> <li></li> <li></li> <li></li> </ul> JavaScript (function() { var item = ...

Implementing a universal timer for tmi.js and discord.js integration

I am currently working on a Discord bot that monitors multiple Twitch chats for commands and executes them on Discord using tmi.js and discord.js. Everything is functioning as expected, but I am facing an issue with implementing a global cooldown on the ...

Get the div to occupy the rest of the available height

I am facing a challenge with two divs on my webpage. The bottom one contains content that expands the highest. The page is set to 100% height and width using the CSS property position: absolute. <style> body, html { height:100%, width:100% } ...

In an AngularJS custom filter function, the error message "keys is not defined" is displayed

As I was reviewing examples in an Angular JS book, I came across a concept that has left me puzzled. It involves the use of custom filters with ng-repeat. Below are the code snippets: <a ng-click="selectCategory()" class="btn btn-block btn-default btn- ...

Using JavaScript within Razor C#

I am attempting to invoke a JavaScript function from within a helper method in Razor. Here is a snippet of my code: @helper MyMethod() { for (int i = 0; i < 5; i++) { drawMe(i) } } The drawMe function is defined in an externa ...

Utilizing PHP Variables in an External JavaScript: A Step-by-Step Guide

I am attempting to utilize an array generated in PHP within my external JavaScript. My PHP code retrieves images from a directory based on the user ID provided via URL and stores them in an array. I aim to use this array in JavaScript to create a photo sli ...

Safari Displaying Error Message "Unhandled Promise Rejection: [object DOMError]" While Playing MP4 Video

I am facing an issue with playing a group of MP4 videos on hover in a container. You can view a demonstration by clicking the link below: While this functionality works smoothly in Chrome, it seems to be causing problems in Safari. Upon hovering, the vide ...

JavaScript functioning properly in Google Chrome and Firefox but not in Internet Explorer 9

Welcome to the Lottery random generator tool! Feel free to use this in Google Chrome or Firefox, but please note that it may not work properly in Internet Explorer 9. If you encounter any issues while using this tool on IE9 and receive an error message st ...

Graphical Interface for an HTTPAPI

After successfully building a REST API in Node.js using Express that includes queue functionalities, my next goal is to develop a web interface for this API. As a newcomer to JavaScript and Node.js, I would greatly appreciate any advice or guidance on ho ...

the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS { 'object Object': '' } //when using JSON.stringify: { '{"A":"a","B":"b","C":"c"}': &apo ...

Searching for a file in Mongoose using an array field of IDs

I am working on a system with two models, Trade and Work, that serve as categories and subcategories of labor. I am trying to implement a feature where new additions automatically select a Trade based on the given Work. However, I am facing challenges in f ...

Guide to adding information to a file in Nodejs depending on a condition

Looking for assistance on how to append an annotation (@Circuit(name = backendB)) to a file if the "createEvent" name exists and the annotation is not already present. I am unsure of the process, so any help on checking and appending using streams would ...

Having trouble navigating to the bottom of a VUEJS app?

I've been working on developing a chatbot app that utilizes a REST API to stream content. While the functionality of the app is running smoothly, I have encountered an issue with the scroll to bottom feature. Instead of automatically scrolling to disp ...

Mastering the art of iterating through a JSON response

Looking to populate a combobox with data from the database. Upon accessing mystream.php?theLocation=NewYork, I receive the following JSON response: RESULT {"result": [{"theID":"36"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork ...

What is the purpose of employing this expression in the context of requestAnimationFrame?

Can you explain the purpose of using this specific "if" statement in relation to requestAnimationFrame? if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime ...

Utilizing Google Script to extract information from Gmail emails and transfer it to Google Sheets

I am facing a challenge with extracting data from an email and inputting it into a Google Sheet. While most of my code is functioning properly, I'm struggling with the regex section due to lack of expertise in this area. Below is a snippet of the HTM ...

Guide to creating a new window without a menu bar for an onclick function in electronJS

After trying to remove the menu bar from the main window using win.setMenu(null) in the main.js file, I encountered a new issue. When opening a new window (referred to as the "add items window"), I struggled to find a way to hide the menu bar in it as well ...

Function being called by Intersection Observer at an inappropriate moment

After running the page, the intersection observer behaves exactly as desired. However, upon reloading the page, I am automatically taken back to the top of the page (which is expected). Strangely though, when the viewport interacts with the target elemen ...

I encountered a permission denied error while attempting to execute the command npm install -g tsc

My main objective is to convert TypeScript code to JavaScript. However, when I attempted to install the TypeScript compiler globally using 'npm install -g tsc', I encountered the following error: npm ERR! Error: EACCES: permission denied, rename ...