Searching for the object that occurs an uneven number of times

Currently, I am tackling a challenge on Codewars that requires identifying the element in an array that occurs an odd number of times. The current solution I have successfully passes 3 out of 6 tests.

function findOdd(A) {
  //happy coding!
  let odd = "";
  let count = 0;
  for (let i = 0; i < A.length; i++){
     for (let j = 0; j < A.length; j++){
      if (A[i] === A[j] ){
        count++;
        }
       if (count %2 != 0){
         odd = A[i];
       }
    } 
  }
  return odd;
}

The following are the test cases that did not pass:

A1: [ 1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5 ]
Expected result: -1

A2: [ 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1 ]
Expected result: 10

A3: [ 5, 4, 3, 2, 1, 5, 4, 3, 2, 10, 10 ]
Expected result: 1

Meanwhile, the following are the test cases that succeeded:

A4: [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]
Expected result: 5

A5: [ 20, 1, 1, 2, 2, 3, 3, 5, 5, 4, 20, 4, 5 ]
Expected result: 5

A6: [ 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1 ]
Expected result: 10

Here, A1 - A6 represent the input arrays and n1 - n6 denote the expected outcomes.

Answer №1

By utilizing the Array.prototype.reduce method, you can create a new object that stores the count of duplicate elements.

With this object, it becomes possible to identify the element with an odd number of duplicates in an array.

function findOdd(A) {
  const countArr = A.reduce((acc, cur) => {
    acc[cur] ? acc[cur] ++ : acc[cur] = 1;
    return acc;
  }, {});
  
  const odd = Object.keys(countArr).find((key) => countArr[key] % 2);
  return +odd;
}

console.log('n1 = ', findOdd([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]));
console.log('n2 = ', findOdd([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]));
console.log('n3 = ', findOdd([5, 4, 3, 2, 1, 5, 4, 3, 2, 10, 10]));
console.log('n4 = ', findOdd([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]));
console.log('n5 = ', findOdd([20, 1, 1, 2, 2, 3, 3, 5, 5, 4, 20, 4, 5]));
console.log('n6 = ', findOdd([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]));

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

Looping through two arrays of objects using Angular's NgFor directive

I need to iterate through two separate arrays using ngFor in order to display their content in an html format. <div class="form-check ml-5" *ngFor="let item of competencias.competencias; let i = index"> <input class=" ...

When utilizing the React onclick function, it generates an increase in state values rather than modifying

I'm currently working on a function that changes the state property, "changedMarkup", when a button is clicked. Initialization constructor() { super(); this.state = { value: 0, changedMarkup: 0 }; } Render Function render() ...

Steps for including a subdocument within a mongoose schema

I am currently working on setting up a subdocument within a mongoose schema using node.js/Express. There are two schemas in play: Member and Address Member.js // app/models/member.js // Loading mongoose to define the model var mongoose = require(' ...

Managing Input Type Dropdown Selections Using Jquery

I am currently in the process of developing a website. On this website, there is a form that includes 3 dropdown menus as shown below. I would like to implement a feature where selecting the number 5 from the Adults menu will automatically display 5 in the ...

Arranging a multidimensional array by various values

I have an array structured like this: Array ( [341] => Array ( [id] => 2034 [name] => Basic [file] => 577688a31d889.svg [order] => 12 ) [342] => Array ( [id] => 2065 [na ...

Can you explain the distinction between setting abc.p as undefined versus deleting abc.p?

The variable abc is pointing to an object. What distinguishes abc.p = undefined from delete abc.p aside from their return values? ...

Push information into MongoDB without the need to make changes to the entire entry within the MEAN stack

I have a MEAN Stack single-page application up and running for managing exams. The schema/model I have for an exam (or Klausur in German) looks like this: var KlausurSchema = new Schema( { name: String, semester: String, krankm ...

Adjust the jQuery.ScrollTo plugin to smoothly scroll an element to the middle of the page both vertically and horizontally, or towards the center as much as possible

Visit this link for more information Have you noticed that when scrolling to an element positioned to the left of your current scroll position, only half of the element is visible? It would be ideal if the entire element could be visible and even centere ...

I'm having trouble getting PHP/AJAX to return the expected XML data - it keeps

I have a JavaScript script that looks like this: function showItems(type) { var xmlhttp = new XMLHttpRequest(); //creating object var call = "getitems"; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState ...

Utilizing the power of functional programming with Javascript to perform mapping

In order to address a fundamental issue involving list indexes, I am seeking a functional solution. To illustrate this problem in the context of React and ramda, consider the following example. const R = require('ramda'); const array = ["foo", ...

Invalid for the purpose of storage

Encountering the following error message: The dollar ($) prefixed field '$size' in 'analytics.visits.amounts..$size' is not valid for storage. return Manager.updateMany({}, { $push: { & ...

Tips for sending and accessing multiple parameters in a URL for Node.js/Express GET routes

Currently, I have figured out how to successfully send and access one parameter in my GET router. However, I am unsure of how to send and access multiple parameters in the same way. Below is the code snippet demonstrating how I currently send and retrieve ...

Ways to ascertain if a view has completed rendering in JavaScript

I am currently building my application using the awesome backbone.js framework. Within my code, I have this layoutView that handles rendering the overall layout and also includes a smaller profile section. The dilemma I'm facing is with the timing o ...

How to change elements within an HTML string using jQuery

I am facing an issue where I have an HTML string (not DOM) that needs to be manipulated using jQuery. However, the code I am trying does not seem to work as expected: var html = '<div><h4><a class="preview-target" href="content.html"&g ...

Displaying Previously Selected Value in HTML Dropdown Menu

Using a combination of PHP and HTML, I have created an HTML table that is generated using a PHP while loop. The dropdown menu on the page displays all distinct portfolio names from my MySQL database by executing the following code: $query2 = "SELECT DISTI ...

Leverage PHP's class construct to transform numerical keys into string identifiers for more organized data collection

I am currently exploring the usage of data collection objects and am interested in employing the class construct to modify the array keys of arrays that are passed to a newly created object. The primary concept involves passing arrays with numerical keys, ...

Storing Images in MySQL Database with JavaScript and Node.js: A Step-by-Step Guide

I am using Javascript to capture an image and store it in a MySQL Database. Below is the code I have written for this: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device- ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

"Customizing FusionCharts: A step-by-step guide to changing the background color

Is there a way to modify the background color of fusionchart from white to black? Additionally, how can I change the font color in the chart? https://i.sstatic.net/MMuIq.png ...

Route.get() is looking for a callback function, but instead received an [object Promise]

Currently, I am in the process of developing a REST API using express and following the architecture outlined in this particular article. Essentially, the setup involves a router that calls a controller. Let me provide you with an example of how a call is ...