Having trouble with a JavaScript function that is supposed to tally up all distinct elements in an array

I had the idea to develop a function that can count all the unique items in an array, but for some reason, I am not seeing any results. Here is the array I am working with: let arr = ["hi", "hello", "hi"];

This is the code snippet I have come up with so far:

function countUnique(arr) {
  var counts = {};
  for (var i = 0; i < arr.length; i++) {
    counts[arr[i]] = 1 + (counts[arr[i]] || 0);
  }

  countUnique(arr);
}

console.log(countUnique(arr));

Answer №1

While you are correctly counting values, the issue arises when you call the method recursively countUnique(arr);, leading to a "call stack exceeded" error. To resolve this, simply eliminate the recursive call and return the counted value counts:

function countUnique(arr) {
  var counts = {};
  for (var i = 0; i < arr.length; i++) {
    counts[arr[i]] = 1 + (counts[arr[i]] || 0);
  }

  return counts;
}

let arr = ["hi", "hello", "hi"];
console.log(countUnique(arr));

The JavaScript engine has a limit on recursion depth. It's usually around 10000, with some engines allowing more.

Answer №2

If you want to find the number of unique elements in an array, you can create a Set and then return its size.

const countUniqueElements = arr => new Set(arr).size;

console.log(countUniqueElements(["apple", "banana", "apple"]));

Answer №3

let array = ["hey", "hi", "hey there"];

function findUniqueValues(arr) {
  var uniqueCounts = {};
  for (var j = 0; j < arr.length; j++) {
    if(arr[j] in uniqueCounts) {
      uniqueCounts[arr[j]]++;
    } else {
      uniqueCounts[arr[j]] = 1;
    }
  }
  return Object.keys(uniqueCounts).length;
}

console.log(findUniqueValues(array));

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

Errors in Intellisense detected within the latest Node Tools Express App development project

After setting up a new project with the "Basic Node.js Express 4 Application" template, I noticed some errors have already surfaced: https://i.sstatic.net/8jbYt.png Could this be a Visual Studio issue? Any pointers on resolving these errors? ...

What is the best way to display the legend on my PieChart?

I am attempting to display the names of colors in my PieChart as a legend. Here is the JSON data: { "choice": "20-29 yrs. old", "count": 4 }, { "choice": "30-39 yrs. old", "count": 2 }, { "ch ...

Despite locating the button, Protractor still encounters difficulties when attempting to click on it

I've been having trouble clicking on a button using Protractor. The issue is that even though the driver can locate the element, it still won't click on it. Any assistance would be greatly appreciated. Thank you in advance. Here is the HTML for ...

Utilizing jQuery to load form(s), submit data via POST method, and fetch results without refreshing the

After conducting thorough research, I have been unsuccessful in implementing any of the solutions I have come across. It seems like I am close to a solution, but there may be something crucial that I am missing... A question similar to mine was asked on t ...

Node.js script terminated: Process concluded with an exit code 139 due to being interrupted by signal 11 (SIGSEGV)

I'm encountering a frustrating issue with my script - it keeps crashing and the debugger isn't able to pinpoint the error. I've attempted using try-catch blocks, but they just don't seem to work. Any recommendations on how I can better ...

Guide on incorporating factories with Ionic/Angular JS while utilizing phonegap

I've been experimenting with global variables in my ionic/angular + phonegap app project by implementing a factory service. However, even adding a simple factory service like the one below somehow disrupts the app and causes all screens to turn compl ...

What is the best way to transfer the value of a radio button, retrieved from a database, to a textbox?

Greetings, I am trying to figure out how to pass the value of a radio button to a textbox using jQuery and PHP. The radio buttons are generated dynamically based on rows from my database, so I set the row ID as the ID for each radio button. However, the co ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Verifying the Compatibility of Linear Gradient in CSS

To verify support for CSS properties such as border-radius, use the following code snippet: if(document.createElement('test').style.borderRadius===''){ //some code } But how can I check for support of linear gradients? The declaration ...

executing a javascript function in PHP following form submission

Having trouble calling a javascript function after submitting a form and experiencing errors? New to PHP and seeking assistance. Any advice is appreciated. if(!empty($varAccountType)) { <?php if($varAccountType=='Free Account') { ...

JavaScript does not function properly with dynamically loaded content

Trying to load the page content using the JQuery load() method. See below for the code snippet: $(window).ready(function() { $('#content').load('views/login.html'); }); .mdl-layout { align-items: center; justify-content: center ...

Reading JavaScript files using the HTML 5 File Reader

Currently, I am working on a feature that allows users to drag and drop a folder containing JavaScript files into an HTML5 page. Here is the code snippet for my implementation: $scope.files = []; //Establish dropzone var dropbox; dropbox = document.getEle ...

How can I effectively utilize find, match, and filter functions with a reactive array in VueJS?

Having some trouble with understanding .value! :) I'm currently working with VueJS v3 and the Composition API. My goal is to locate the first matching value in a reactive array of people. Typically, this array would be populated through an API call, ...

Extract the content of a textbox within an iframe located in the parent window

Is it possible to retrieve the value of a text box in an iframe from the parent page upon clicking a button? Below is an example code snippet showcasing the situation: <div> <iframe src="test.html" > <input type=text id="parent_text"> & ...

Node.js server experiences a crash after attempting to send a large string using res.send()

I've recently started learning JavaScript and NodeJs. I'm facing an issue with my Nodejs application crashing when a get request is made, specifically when trying to return a large string. app.mjs app.get('/log', function (req, res) { ...

Struggling to make the javascript function compatible with the drop-down menu

I'm encountering issues with making my JavaScript work properly alongside my HTML. Specifically, I want the "activity" drop-down box to function in conjunction with the "city" drop-down box. For instance, if I choose "Brisbane" and then select an acti ...

The comments entered into the box are being overridden instead of being posted

I have encountered an issue where, upon hitting the post button, the comment is successfully posted on the page. However, if I hit the button again, it seems to override the previous comment. Can someone please provide clarification on this matter? Additio ...

Tips for sorting data by date in Angular 4

Seeking guidance on how to filter records in a table based on the date column. The current filtering code is generating an error message: ERROR TypeError: Cannot read property 'indexOf' of null temp = [{ "firstName":"Ravi", "date":"2019-04-0 ...

Adjusting the width of a Material UI drawer: Tips and tricks

Currently, I am working on implementing the Material UI drawer and anchoring it to the top of my page. It is functioning correctly, however, I am encountering an issue where I am unable to adjust the width of the drawer. Despite trying to update the width ...

Using an image tag with dual quotes in Vue.js

I am currently working on a feature where users can upload an image and then have it displayed after the upload is complete. However, I am facing an issue where the response link of the image contains a double quote, and when I use the <img> tag to ...