Is there a way to identify the duplicates within an array of numbers and also determine how many times each number is repeated?

Is there a way to find duplicates in an array that appear two or more times? For example, if I have an array of strings like this:

var arrStr = 'i do as as becasue i do as';

function CheckDuplicates(sentence)
{
  let arr = sentence.split(" ");
  let counter = {};
  let duplicates = [];

  for(let i = 0;i < arr.length;i++)
  {
    let item = arr[i];
    counter[item] = counter[item] >= 1 ? counter[item] += 1 : 1;
    if(item != "")
    {
      if(counter[item] == 2)
      {
        duplicates.push(item);
      }
    }
  }

  Object.keys(counter)
  .filter(key => !duplicates.includes(key))
  .forEach(k => delete counter[k]);

  return {
    duplicates: duplicates,
    counter: counter
  };

}

let r = CheckDuplicates(arrStr);

console.log(r.duplicates);
console.log(r.counter);

The console output would be:

["as", "i", "do"]
{i: 2, do: 2, as: 3}

However, when trying the same code with an array of numbers, the result is not as expected:

It shows {} in the console.log(r.counter);

Seems like the includes method does not work correctly with numbers. Here's an example with an array of numbers:


var arr = [9, 9,  9 ,111, 2, 3, 4, 4, 5, 7 , 7];

function CheckDuplicates(sentence)
{
  let counter = {};
  let duplicates = [];

  for(let i = 0;i < arr.length;i++)
  {
    let item = arr[i];
    counter[item] = counter[item] >= 1 ? counter[item] += 1 : 1;
    if(item != "")
    {
      if(counter[item] == 2)
      {
        duplicates.push(item);
      }
    }
  }

  Object.keys(counter)
  .filter(key => !duplicates.includes(key))
  .forEach(k => delete counter[k]);

  return {
    duplicates: duplicates,
    counter: counter
  };

}

let r = CheckDuplicates(arr);

console.log(r.duplicates);
console.log(r.counter);

This will result in:

[9, 4, 7]
{}

Answer №1

When using Object.keys, it returns the keys as strings, while includes checks for type equality as well.

Although the commented line was modified to cast to a string when pushing into duplicates, your code is functioning properly. You could also address this by utilizing includes.

var arr = [9, 9,  9 ,111, 2, 3, 4, 4, 5, 7 , 7];

function CheckDuplicates(sentence)
{
  let counter = {};
  let duplicates = [];

  for(let i = 0;i < arr.length;i++)
  {
    let item = arr[i];
    counter[item] = counter[item] >= 1 ? counter[item] += 1 : 1;
    if(item != "")
    {
      if(counter[item] == 2)
      {
        duplicates.push(`${item}`); // casting to string
      }
    }
  }

  Object.keys(counter)
  .filter(key => !duplicates.includes(key))
  .forEach(k => delete counter[k]);

  return {
    duplicates: duplicates,
    counter: counter
  };

}


let r = CheckDuplicates(arr);

console.log(r.duplicates);
console.log(r.counter);

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

What is the best way to display a page within a div when clicking in Yii?

I'm trying to use the jQuery function .load() to load a page into a specific div. Here's my code: <a href="" onclick="return false;" id="generalinfo"> <div class="row alert alert-danger"> <h4 class="text-center">Gen ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Is there a way to replicate onbeforeunload in a Vue.js 2 application?

I have a Vue component that is monitoring whether it has unsaved changes. I want to alert the user before they move away from the current form if there are unsaved modifications. In a traditional web application, you could use onbeforeunload. I tried imple ...

Accessing global variables is prohibited for Javascript

I currently have a global variable named calculated_price that stores the price of a specific product. This global variable's value is modified by one function, and then passed to a server via an AJAX post request by another function: var calculated_ ...

Tips for preventing page breaks (when printing or saving as a PDF) in lengthy HTML tables

Here is the link to a single HTML file (including style and scripts): FQ.html The problem I'm facing can be seen in this image: https://i.sstatic.net/Nr4BZ.png I've tried several solutions, the latest of which involves the following CSS... @me ...

Getting files from a server in ReactJS: Step-by-step guide

Currently, I am utilizing an API to retrieve file paths from the server. However, I am looking to enhance the functionality by allowing users to download these files upon clicking on them. To achieve this, I am leveraging the react js-file download package ...

Eliminate unnecessary components during the JSON to CSV conversion process

I have a JSON data set that looks like this: {"id":1,"name":"Sam","birthday":"12December","age":"15"}, {"id":2,"name":"Ash","birthday":"12January","age":"23"} After passing the data through the function: ConvertToCSV(data) I can extract id, name, birth ...

Using jQuery to store the name of a Div in a variable and subsequently invoking it in a function

Recently, I've been grappling with a task involving storing a div name in a variable for easier editing and incorporating it into standard actions like show/hide. My code functions perfectly without the variables, but introducing them causes the div ...

The organizational chart function was functioning properly on the local environment, however, it failed to work after deployment, resulting in the error message "jQuery(

Currently, I am in the process of creating an organizational chart using the Angular library called orgchart. The code I have developed works fine on my local machine, but when we deploy it onto our nginx server, we encounter an error related to jQuery. T ...

Obtain the properties of a sphere in three.js when it is hovered over with the mouse

In my current project, I am creating a series of spherical objects using three.js by utilizing an array and a for loop. The initial array structure is as follows: atoms = [ ['Na', [0, 0, 0]], ['Na', [0.5, 0.5, 0]], ['Na', ...

Can different classes be assigned as "dragenter" targets?

Is it possible to apply the Jquery "dragenter" event to multiple targets or classes simultaneously? I tried this approach, but it doesn't seem to be working: $('.list').on('dragenter','.class1, .class2', function(e) { ...

Is it possible to apply styles to javascript elements without relying on img class? Additionally, how can I incorporate an onclick button while maintaining a fully functional navigation bar?

My current project involves creating an interactive collage where users can click around and have pictures pop up at the clicked location. The functionality works as intended, but now I'm facing issues with the navigation bar not being clickable. Addi ...

Finding out the nature of nullable attributes within an object: How can it be done?

I'm facing an issue with saving incomplete forms where I have a form being filled out by a user and I wish to allow the form to be saved even if it's not fully complete. Before sending the object to my API, I need to set any null attributes to e ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

transferring an item through ng-repeat

<td ng-repeat="data in data_legend" rowspan="2"></td> Within this code snippet, the data_legend variable is a dynamic array that users populate through a Form. The goal here is to showcase all the dynamic content to the user and determine whic ...

how can I insert an asp textbox into a div using jquery?

I have an asp.net textbox (<asp:TextBox></asp:TextBox>), and I would like it so that when I click a button, the textbox is placed inside a div like this output (<div><asp:TextBox></asp:TextBox></div>). I tried using the ...

Can a webpage be sent to a particular Chromecast device without using the extension through programming?

My organization has strategically placed multiple Chromecasts across our facility, each dedicated to displaying a different webpage based on its location. Within my database, I maintain a record of the Chromecast names and their corresponding URLs. These d ...

Partially accessible Angular service within a callback function

I'm currently facing an issue in my Angular simple app related to a factory that is not fully available within a callback function. You can check out a simplified version of the application on this Plunkr link. Here's a snippet of the code: Th ...

Having trouble with sending an ajax PUT request

UPDATE: The issue of getting an undefined URI was resolved by storing $(this).attr('red') in a variable. However, the 500 Server error persists. UPDATE: For reference, the complete code can be found on GitHub. Just to ensure nothing was overlook ...

Instructions on creating a solid wall in Three.js using boxGeometry to prevent objects from passing through

I recently created a 3D maze using threejs, where I utilized BoxGeometry to construct walls that the game object cannot pass through. In my research, I discovered the importance of collision detection in ensuring the object does not go through the wall. ...