How to tally duplicate values in an array using Javascript

I'm honing my algorithm skills and challenging myself to write my own code rather than relying on existing solutions. It's a fun way for me to gauge my understanding.

INPUT:

arr1 = ['asd','ew','lol','asd']

EXPECTED OUTPUT:

{ asd: 2, ew: 1, lol: 1 }

This is my implementation:

arr1 = ['asd', 'ew', 'lol', 'asd']
      arr2 = []
      results = {}

function checkIfExists(word) {
  if (arr2.length != 0) {
    for (i = 0; i < arr2.length; i++) {
      if (arr2[i] == word) {
        results[word] += 1
      } else {
        arr2.push(word)
        results[word] = 1
      }
    }
  } else {
    arr2.push(word)
    results[word] = 1
  }

for (i = 0; i < arr1.length; i++) {
  checkIfExists(arr1[i])
}
console.log(results)

ACTUAL OUTPUT:

{ asd: 2, ew: 2 }

Answer №1

Make sure not to use i as a global variable, as it can lead to issues when used in multiple loops. Another mistake is in the increment algorithm where there are more counts added to the results array than necessary. Here's an improved approach:

arr1 = ['cat','dog','fish','cat']
arr2 = [] 
results = {}

function checkIfExists(word){
    if (arr2.length != 0){
        var exists = false;
        for (var j = 0; j < arr2.length; j++){
            if(arr2[j] == word){
                results[word] += 1
                exists = true;
                break;          
            }
        }
        if(!exists) {
            arr2.push(word)
            results[word] = 1
        }
    }else{
        arr2.push(word)
        results[word] = 1 
    }
}

for (var k = 0; k < arr1.length; k++) {
    checkIfExists(arr1[k])
}
console.log(results) 

Answer №2

Upon initial inspection, I have pinpointed three questions that you may have intended to pose.

  1. What issues are present in my code?
    • Summarizing the situation succinctly is best done by referencing Felix Klings comment:

      The main problem is not utilizing var to declare i.

    • The loop, seemingly designed to find an element within arr2, actually leads to multiple modifications of arr2... quite prominently!
  2. Why is my code generating inaccurate results? Although your code correctly produces output based on the applied logic, it seems probable that the intended logic does not align with what you had in mind. This scenario is quite common.
  3. How can I rectify my code?
    • Initiate improvements by altering your loop patterns from for (i = ...) to for (var i = ...).
    • Consider the specific objective of the said loop. If its purpose entails locating an item within arr2, then there should be no necessity for altering arr2 during this process. It's possible that the loop itself might be unnecessary;
      1. You could substitute the entire loop with Array.prototype.indexOf or Array.prototype.includes!
      2. You could potentially replace the complete function with
        function checkIfExists(word) { results[word] = arr1.filter(function(w) { return w === word; }).length; }
        !
      3. Enhancing your comprehension in designing functions would be beneficial, so exploring certain aspects in this code might prove helpful:

var arr1 = ['asd','ew','lol','asd'];
var result = arr1.reduce(function(result, w) { result[w] = result[w] || 0;
                                               result[w]++;
                                               return result;              }, {}));
console.log(result);

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

The key property is present on the list item, yet the key warning persists

I have encountered various issues with this problem, but I am unable to pinpoint the exact cause. I am not extracting individual list items and simply displaying a UL with unique keys assigned to each item. However, when I log the results, I see something ...

Creating a new database row dynamically with PHP, JavaScript, and AJAX

There is a button that triggers a popup box with a textfield when clicked. Once something is entered in the textfield and the "Add" button is clicked, it should be added to the database. Currently, upon clicking "Add", data is inserted into the DB but it ...

Decoding JSON information within WordPress

I'm looking to retrieve Instagram user account information such as followers, following, and account name. The endpoint I have been using is: https://www.instagram.com/{username}/?__a=1 By including the specific username in the endpoint URL, I am a ...

ui-scroll - unable to return to the start of the list

How can I achieve a scroll downwards and then return to the beginning of the list? I've searched for examples on how to implement ui-scroll back and forth, but none seem to fit my needs. Please assist. You can find the fiddle here: http://jsfiddl ...

Transforming Yii1 code into Yii2 code (altering the language component)

I am facing an issue. I have a code in Yii1 that allows me to change the language on my site. echo CHtml::ajaxLink('EN', array('/'), array( 'type' => 'POST', 'success' => 'j ...

Utilizing browser and CDNs to import modules in threejs and three-globe for seamless integration

As I delve into the world of threejs and three-globe, I encounter a challenge when trying to integrate them using CDN distributions from unpkg. The issue lies in dealing with modules, and I'm considering the possibility of incorporating a build tool d ...

Syntax of the Vue.js application object model

Just delving into the world of vue.js and stumbled upon this code snippet. Curious to know more about its structure. const CounterApp = { data() { return { counter: 0 } }, mounted() { setInterval(() => { this.counter++ ...

How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields. I understand how to select the value itself: Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; })) ... but I am unsur ...

Utilizing Jquery to apply CSS styles to three div elements sequentially with a timed loop of N seconds for each

I have 3 different HTML divs as shown below: HTML <div id="one" class="hide">Text one</div> <div id="two" >Text two</div> <div id="three" class="hide">Text three</div> I am looking to use jQuery to dynamically change ...

A program that removes rows while also decreasing the overall sum

I have implemented a form that allows users to add labor and its price, while also displaying the assigned labor on the same page underneath. My objective is to have functionality where if a user clicks on delete, it will remove the corresponding table ro ...

Using TypeScript generics with the `keyof` operator may result in rejection

I created a custom method using the RXJS library which looks like this : function Subject<T>(t: T):T { return t; } In addition, I defined an interface that specifies the structure of my application values. Additional keys can be added to this i ...

Switching Databases in MongoDB after establishing a connection using Express - A guide

I am currently using Express to establish a connection with my MongoDB database: mongodb.MongoClient.connect(mongourl, function(err, database) { // Is there a way to switch to another database at this point? }); In the initial setup, I have to co ...

When attempting to rotate a sphere in threejs, the rotation may not function properly if a loop is

I am attempting to rotate a sphere a specified number of times when a button is clicked (with the user selecting the number of rotations). To achieve this, I have implemented a for loop: $('#clickme').on('click', function () { var ...

The rate limit feature in NextJS does not function properly when used with middleware

Currently, I have implemented a rate limit using the lru-cache based on the official example provided by Vercel, and it is functioning flawlessly. My intention was to consolidate the try-catch block in a Middleware to handle all routes, instead of duplica ...

Transferring state information from a JSX navigation bar to a JSX map component in React

I'm having trouble figuring out how to utilize React in order to pass the state of my navigation bar to my map component. Essentially, I am fetching a date from the navigation bar and need to use it within my map component to display certain elements ...

Guide for accessing an array property from an observable-wrapped class in Angular

I am currently facing a challenge in filling a dropdown menu by retrieving an array property from a class that is encapsulated within an observable. Here is an example of my interface: export interface IApplicationConfigurationResponse { settings?: Set ...

Display Razor code in a JavaScript function once the webpage has finished loading

$("body").on("click", "#ActionButton", function (e) { //set current select index currentBook = $(this).attr("data-bookId"); //set title $("#BookAction .modal-title").text('@Model[currentBook].BookName&a ...

Employing chained async/await function executions

I am currently troubleshooting a straightforward code. The problem lies within an async function I've created: async function updateResult(event){ let result = db.fetchResult(event.ProcessId); return result; } This function is being called from ...

Strip all whitespace from an entire HTML document, excluding any content within a <pre> tag,

While working on ASP.NET MVC 3, I implemented an Action Filter to remove white spaces from the entire HTML. It has been functioning as expected most of the time but now I need to tailor the RegEx so that it does not affect content inside the pre element. ...

The Material UI Select Component has the ability to transform a controlled text input into an uncontrolled one

I encountered a warning in the console while trying to update the value of a Select input. The warning message is as follows: index.js:1446 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not swi ...