JS Code: Develop a function that generates a distribution analysis of an array

I have been working on a function that calculates the frequency distribution of an array. The aim is to output an object in which the keys represent the unique elements and the values show how frequently those elements appear.

Here's the code I've written so far:

function getFrequencies(arr) {

  let obj = {}; 

  for (let i=0; i<arr.length; i++){
    let element = arr[i]; 

    console.log(element)

    // check if key exists in the object already

    // if it does, increment its value by 1
    if (obj[element] !== undefined){
      obj[element] += 1;
    }

    // if it doesn't, set the initial value to 1
    else {
      obj[element] === 1; 
    }
  }
  return obj
}

Upon calling getFrequencies(["A", "B", "A", "A", "A"]), my current code gives an empty object instead of the expected result:

{ A: 4, B: 1 }

I'm wondering what errors might be present in my implementation?

Answer №1

obj[element] === 1; this is comparing values, not assigning them.

To assign a value of 1 to obj[element], use the syntax: obj[element] = 1;

An easier way to achieve this in ES6+ is:

arr.reduce((acc, item) => {
  acc[item] = (acc[item] || 0) + 1;
  return acc;
}, {});

Answer №2

The issue in your code is that you are using equality instead of assignment in the else part.

obj[element] === 1;

You should change it to

obj[element] = 1;

This way, your code will properly initialize keys on obj

function calculateFrequencies(inputArr) {
  let obj = {};
  for (let i = 0; i < inputArr.length; i++) {
    let element = inputArr[i];
    if (obj[element] !== undefined) {
      obj[element] += 1;
      console.log(obj, 'inside if')
    }
    else {
      obj[element] === 1;
      console.log(obj, 'inside else')
    }
  }
  return obj
}

console.log(calculateFrequencies(["A", "B", "A", "A", "A"]));

An alternative approach is to use the reduce method

function calculateFrequencies(inputArr) {
  return inputArr.reduce((result, item) => {
    result[item] = result[item] || 0;
    result[item]++;
    return result;
  },{});
}

console.log(calculateFrequencies(["A", "B", "A", "A", "A"]));

Answer №3

Within your else section, ensure you are performing assignment instead of strict comparison, like so:

obj[element] = 1; 

Rather than:

obj[element] === 1;

Take a look at the functional demonstration provided below:

function calculateOccurrences(array) {

  let obj = {}; 

  for (let i=0; i<array.length; i++){
    let element = array[i]; 

    console.log(element)

    // Check if key already exists in object

    // If it does, increment the value by 1
    if (obj[element] !== undefined){
      obj[element] += 1;
    }

    // If it doesn't exist, assign 1 to initialize future elements
    else {
      obj[element] = 1; 
    }
  }
  return obj
}

console.log(calculateOccurrences(["A", "B", "A", "A", "A"]));

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 function vue.findIndex is not recognized as a valid function

Encountered an issue with the findIndex() function Uncaught (in promise) TypeError: state.carts.findIndex is not a function The cartId includes rowId, qty, sizeVal, and image Methods updateCart() { this.$store.dispatch('updateCart&apos ...

Cookie fails to transmit upon deploying my application on Vercel

After developing a straightforward authentication system using cookies and expressjs, everything was running smoothly on my local environment. However, upon deployment to Vercel, I encountered issues where the program code was not executing properly (cooki ...

Sending data retrieved asynchronously to child components' props

Currently, I am developing an application that fetches an array of news items from a remote source and showcases them on a webpage. After successfully calling the endpoint using $.getJSON(), as indicated by console logs, I integrated this call into the pa ...

User creation causing redirection malfunction

Recently, while working on a website, I encountered an issue with the registration process for users. It was functioning properly when I tested it a few days ago. After making some updates to other aspects of the website such as the login and profile sect ...

What is the best way to upload this array into the system's memory?

I recently stored an array by using the code below: NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray]; [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"myArray"]; Could you provide the code needed to retrieve this array ba ...

What are some ways to bypass a closed Google form that is no longer accepting responses? I need to find a way to submit my form even after the deadline

Is there a way to trick a closed Google form that says it is "no longer accepting responses"? I'm looking to submit a form past the deadline. Is there a method to access and submit a form that has already been closed? The code for the closed form appe ...

Navigating the world of gtag and google_tag_manager: untangling

Tracking custom events in my react application using Google Analytics has been successful. Initially, I followed a helpful document recommending the use of the gtag method over the ga method for logging calls. The implementation through Google Tag Manager ...

Moving icon that appears when hovering over a menu button

Before diving into this, please take a moment to visit the following website to understand my goal: You'll notice there is a noticeable RED arrow positioned below the menu. What I aim to accomplish is... when I hover over a menu button, the arrow smo ...

Prevent Angular Material Autocomplete from automatically updating the input field

As part of my project, I am working on creating a country autocomplete input feature. To make the input more reusable, I am looking to turn it into a component using the ControlValueAccessor interface. The goal is to have the component accept a FormControl ...

The Bootstrap4 nav-tabs are mistakenly causing the entire page to change instead of just the tab content

After encountering an issue on my Angular site while trying to incorporate a bootstrap nav-tab element, I decided to refer to some example code from the official Bootstrap documentation here. The problem arose when clicking on the tabs of my page resulted ...

Collection of ArrayLists containing Integers populated with varying combinations

If I have an array of Integer Wrap Objects... Integer[] p = new Integer[]{7, 5, 3, 2}; //Variable Length I need to create an array of ArrayList with specific values. 2 3 3, 2 5 5, 2 5, 3 5, 3, 2 7 7, 2 7, 3 7, 3, 2 7, 5 7, 5, 2 7, 5, 3, 2 7, 5, 3, 2 W ...

Arrangement of Bootstrap card components

Each card contains dynamic content fetched from the backend. <div *ngFor="let cardData of dataArray"> <div class="card-header"> <div [innerHtml]="cardData.headerContent"></div> </div> <d ...

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

Raycasting for collision detection is not very precise

I am facing a challenge in my project where I have multiple irregular shapes like triangles, trapezoids, and other custom designs in a 2D scene all located on the Y=0 axis. I am currently working on writing code for collision detection between these shapes ...

Looping through jQuery click() function

I used a loop to generate div elements and I am trying to modify the background-color when the div is clicked. var c = $("#container")[0]; for(var i=0; i<6; i++){ var x = document.createElement("div"); x.className = "sqare"; x.click(changecolor(t ...

Is there a way to transform vanilla JavaScript code into Vue.js code?

// Vanilla JS Code Conversion const app = new Vue({ el: '#app', methods: { // Logged out Events loginHelp: function() { this.$refs.forgotten.style.display = 'flex'; this.$refs.login.style.display = 'none&apo ...

Issue encountered when transferring properties to create a search bar

My goal is to create a search input that filters based on the user's input. I have two components - one with the search input (app.js) and the other with the table (table.js). In the search input component (app.js), I can retrieve the current value b ...

Take out a portion of text from a larger string, divide the remaining text into smaller parts, and then save

Here is the code I am using: public void processData(string data) { string com = data.Split(' ')[0]; string[] val = data.Remove(0,com.Length).Split(' '); } The objective of this code snippet is to have the variable com s ...

Loading of iframes occurs only after receiving the content sent through the postMessage function

I have a scenario where an iframe is used to receive information through the contentWindow.postMessage function in order to log in to a page that I am creating. However, I am facing an issue where the page loads before the contentWindow.postMessage message ...

What steps are needed to set up app.json to support various connection types for incoming requests, including HTTP?

Within my Expo React Native application, I am encountering issues with fetching data from my Ruby on Rails API due to restrictions on http connections. I have explored various solutions that involve modifying the AndroidManifest.xml in Android and Info.pl ...