Fundamental JavaScript associative object

I am working with an array filled with various items.

let items = {'A', 'A', 'A', 'B', 'B', 'C'}

My goal is to generate a new array that shows the count of each item present in the original array. The expected output should be:

{
  'A': 3,
  'B': 2,
  'C': 1

}    

Answer №1

The primary issue causing the malfunction is that using {} signifies declaring an object, while using [] indicates declaring an array.

Aside from that, the code you provided requires only minimal adjustments.

var items = ['A', 'A', 'A', 'B', 'B', 'C'];

function count(items) {
    var result = [];
    var count = 0; 
    for (var i=0; i<items.length; i++) {
       var item = items[i];


       if(typeof result[item] === 'undefined') {
           //this is the first time we have encountered this key
           //so we initialize its count to 0
           result[item] = 0;
       }

       result[item]++; 
   }

   return result;
}

var result = count(items);
for (var key in result) {
    alert(key + " : " + result[key]);
}

Answer №2

When dealing with an array [] instead of an object {}, this method will function as expected:

var items = ['A', 'A', 'A', 'B', 'B', 'C'];
var o = {}; 
items.forEach(function(element) {
  (element in o) ? o[element]++ : o[element] = 1;  
});

If you have an actual object with keys and values, you can utilize Object.keys() on items to retrieve an 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

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Move my site content to the appropriate location

I am working on a single-paged website built with Jquery and HTML. The main content is housed within a div called #site-content, which has a width of 4400px. Each "page" is positioned within this div, with the first page starting at left: 0px, the second a ...

Can an inner promise in JavaScript not be caught by another promise?

When using promises, I am encountering an issue where the "catch" doesn't seem to catch its child promises. This results in me having to include two instances of the "catch" block. Facility.userHaveAccess(locationObject.created_by, locationObject.fac ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

Multiple clicks causing the button to increment excessively and fire repeatedly

Currently, I am working on a web application that includes a deploy button in one section. When this button is clicked, a modal pops up with two additional buttons, one for confirmation and the other for cancelation. The issue I am facing is that when I c ...

Adjusting the size of a dynamically generated rectangle using DrawingManager

I am currently working on a web application using Azure Maps along with the DrawingManager library. My goal is to allow users to save a drawn rectangle and potentially edit it by resizing later on. The strange thing is that while resizing rectangles works ...

Node.js socket.io: How to Handle Multiple Returned Values from a Single Event

I've been working on a simple chat app using Node, Express (^4.15.3), and socket.io (^2.0.3). However, every time I add a new message, I notice that I get an additional response each time. For instance, when I send the message "Hello" for the first t ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

Is event delegation in React similar to jQuery's `on()` method?

Just starting out with React.js and I've built a list Component that has items being added and removed frequently. Each item needs to have click and/or hover events. I'm looking to implement event delegation similar to how it's done in jQue ...

Managing actions on dynamically generated dropdown options in <select> elements

If I have a function that generates a dropdown, it is called from a parent component where props like state key, array, and onChange function are passed in. The dropdown items are dynamically created from the array. What I want is for the parent's sta ...

Message displayed within Ng-repeat loop

Having trouble implementing a tooltip within an ng-repeat for each item in a td element. Whenever the mouse hovers over an item inside the td, I want a tooltip to display with more details. The code below shows my setup, using ng-if to prevent displaying e ...

The pinFileToIPFS method in Pinata IPFS is currently unable to accept files uploaded by users

Currently, I am immersed in a project where I am utilizing React.js, Express.js, and Node.js to transform a user-provided image into an NFT on the Ethereum blockchain. To achieve this, I must first upload the image to IPFS (Pinata being my choice of servic ...

Calculate the sum in real-time using JavaScript

How can I dynamically compute the sum of subtotals without encountering the following error? document.getElementById("item_subtotal[" + cnt + "]") is null Below is my JavaScript code: function calculateTotalAll(numitems) { var cnt = 1; var tot ...

Error on Node 101: The app.use function is throwing a ReferenceError because the [route]

I am still learning Node/Express and have a question about routing. I encountered an error message that says: app.use('/edu', edu); ^ ReferenceError: edu is not defined at Object.<anonymous> (/Users/ronitelman/Dropbox/happy ...

Can you explain the concept of "declaring an array of characters and an array of integers with the same name"?

Hey, I'm currently learning C programming. I have a challenging task that requires me to declare an array of characters and an array of numbers using the same identifier. The goal is to find the number of repetitions for each number in the number arra ...

How do I find the length of an array in MongoDB?

{ "_id" : 123456, "first_name" : "Jane", "last_name" : "Smith", "hobbies" : [ "reading", "painting", "traveling" ], "location" : { "name" : "Jane Smith", "company" : "TechSolutions", "street" : "123 Main Street", "city" : "Seattle ...

Leverage the selected values to dynamically generate a table using jQuery

Can someone help me figure out how to store multiple values from a selection and then create an array using jQuery? Here's the scenario: In my multiple selection, I have 5 values: <select name="animal" id="animal" multiple="multiple">    ...

Efficiently incorporate a set of fields into a form and automatically produce JSON when submitted

The optimal approach for dynamically adding a set of fields and generating JSON based on key-value pairs upon form submission. <div class="container"> <div class="col-md-4"> <form method="POST" id="myform"> <div class="f ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...

Navigating attributes originating from the key in JSON: A guide to effective management

I'm facing a situation in my application where I have a JSON object structured like this: var pages = { home: { title: "Home", description: "The home page", file: "home.html", url: "/home" }, blog: { ...