Determine the total number of values within a specific Object

const obj1 = {
  1: 'a',
  2: 'b',
  3: 'a',
  4: 'c',
  5: 'a',
  6: 'd',
  7: 'c',
};

The desired output for the given code should be:

output = { a: 3, b:  1, c: 2, d: 1 }

Answer №1

Success with this code!

function countOccurrences(obj) {
  const result = {};

  for (const key in obj) {
    const value = obj[key];
    result[value] = (result[value] || 0) + 1;
  }
  return result;
}
// Input object
const obj1 = {
  1: 'a',
  2: 'b',
  3: 'a',
  4: 'c',
  5: 'a',
  6: 'd',
  7: 'c'
};

// Execute the function
const output = countOccurrences(obj1);
console.log(output); // Result: { a: 3, b: 1, c: 2, d: 1 }

Answer №2

An efficient and concise solution can be implemented as follows:

Object.values(obj1).reduce((o,n)=>{
    if (!o[n]) o[n]=0;
    o[n]+=1;
    return o;
}, {})

The Object.values() method extracts the values of an object (refer to documentation for more information).

By utilizing the Array.protoype.reduce() function, we can apply a specified function on each element of the array and reduce it to a single value with an initial empty object {}. This distinguishes it from the Array.prototype.map method. (see documentation)

To enhance readability, I have chosen the parameter names o for old and n for new within the reduce function. The purpose of this operation is straightforward:

  • Check whether the key n (represented by a initially) exists in the current "old" value (initially an empty object {}). If not, assign a count of 0.
  • Increment the count at o[n] regardless.
  • Return the updated o.

In this case, the accumulator o is continuously passed into and returned by the function, accumulating the counts. Hence, it's often referred to as the accumulator. However, I find old more intuitive than accumulator.

Functions like Array.prototype.map, Array.protoype.reduce (and don't overlook Array.protoype.reduceRight) may seem complex initially, but they become invaluable tools once mastered.

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

In my chat application, I encountered the error message "Received an expression instead of an assignment or function call - no-unused-expressions"

While working on my React Chat app and trying to access my Firebase, I encountered the error message: "Expected an assignment or function call and instead saw an expression no-unused-expressions" The error seems to be related to the assignment of this.rem ...

Switching to a different view in a React Native application

I am encountering difficulties while navigating between pages in my React Native application. Whenever I try to use the button, an error message pops up saying: TypeError: undefined is not an object (evaluating '_this.props.navigation'). My app c ...

Customizing JqGrid to include a button in the advanced search dialog

I am interested in enhancing the advanced search dialog to include a feature that allows users to save a complex query they have built. Although saving the SQL code is not an issue, I need guidance on integrating buttons within the advanced search query d ...

What is the best way to bring the global stylesheet into a Vue component?

Embarking on my first VueJS project, I decided to create a global stylesheet to maintain consistent styles across different components. After installing the SCSS loader and setting up my stylesheets, I encountered an issue. $mainFont: 'PoppinsRegular, ...

Trouble retrieving data from cross-domain JSON request in AngularJS

Struggling all day to retrieve the JSON data from this specific URL: As a beginner in cross-domain calls, I attempted using JSONP and $get.JSON methods without any luck. My main goal is to extract the information from that URL link and store it in an Angu ...

Prevent unauthorized entry to css and javascript files

Is there a way to prevent direct access to a file? I want the file to be used on my website, but I want to block it from being accessed directly. For example, if you try to open this link: https://example.com/style.css, you will see an error message. Howev ...

When the value is inputted into the textbox and the enter key is pressed, a fresh chip displaying the entered value will materialize

Whenever I click on a textbox, a menu opens that requires me to enter a value in the textbox. After entering the value and hitting enter, a new chip with the entered value should appear. I tried creating an Onchange event to pass the values to the chip com ...

The intersectObjects function is failing to retrieve the object from the OBJMTLLoader

Within my scene, I've introduced a new object along with several other cubes. To detect collisions, I'm utilizing the following code snippet that fires a Ray: var ray = new THREE.Raycaster(camera.position, vec); var intersects = ray.intersectObj ...

Using jQuery to retrieve meta tags from another website

I have come across this question before on Stack Overflow, but unfortunately, the solution provided no longer seems to work. I even attempted it myself in this Codepen Demo. However, I encountered an error stating: "XMLHttpRequest cannot load https://vime ...

What is the best way to generate an array populated with specific values from a file?

In the file input.txt, there is a structure like this: n a1 a2 a3 ... an The value of n represents the size of the array, while a1, a2, a3, and an are the elements within that array. I am looking to construct an array containing the objects represented ...

Guide on crafting a scrollable and touch-responsive grid using CSS and JavaScript

I am seeking guidance on creating a grid with a variable number of columns and rows. It should be contained within a separate div and should not interfere with other objects or alter the parent's size. The grid needs to be square and I am currently u ...

The task of renaming a file in javascript when it already exists by incrementing its name like file_1.txt, file_2.txt, and so on is proving to be

After trying out this code snippet, I noticed that it creates a file like file.txt as file_1.txt. However, when I try to use the same filename again, it still shows up as file_1.txt instead of incrementing the number. Is there a way to automatically incr ...

What role do colors and tables play in Javascript?

Preparing for my upcoming Web Development exam, I stumbled upon an intriguing question:https://i.sstatic.net/m9T0F.png Here's how I tackled it: function pallete() { var components = ["00", "33", "66", "99", "CC", "FF"]; var conte ...

The AJAX chat interface is failing to show messages, even after refreshing the page

My JavaScript file is not displaying messages from the PHP file even though they are successfully sent. The messages are present in the PHP file and database, so I'm wondering if there's a mistake in my code. Can anyone suggest an alternative app ...

The prefixes for Ruby on Rails routes are not properly preprocessed in the .erb.js file

I'm currently working with Rails 4 and encountering an issue with the following file: // apps/assets/javascripts/products.js.erb var getColoursAndMaterialsData = function(onSuccess) { var fd = formdata(); $.post( '<%= data_products_ ...

Utilizing MySQL responses in a single function with Node.JS: A comprehensive guide

Here is the Node.JS code snippet I am working with: var mysql= require('mysql'); function first(){ var connection = mysql.createConnection({ host : 'xxxxx', user : 'admin', password : 'xxxxx', datab ...

What is the best way to retrieve data from an external JSON file using jQuery?

This is my app.js file $(document).ready(function () { $.getJSON("http://localhost:3000/db.json", function (data) { $(data.as).each(function (index, value) { console.log(value); }); }); }); and this is db.json f ...

Error: Trying to access the 'name' property of an undefined value in JSON

I encountered an issue displaying the error message below: TypeError: Cannot read properties of undefined (reading 'name') While developing a Discord bot using NodeJS and Discord.js, I have an empty JSON object where I append items whenever a ...

Unable to retrieve the content of Material UI Textfield

I'm new to React and I need help with my login page that uses Firebase authentication. I have an input field to capture the user's contact information for validation, but I'm having trouble retrieving this data. I've tried various solut ...

The proper method for redirecting the view after a successful AJAX request in a MVC application

Explanation of the Issue: I have added a search function to the header section of my MVC website. It includes an input text box and a 'Search' button. The Problem at Hand: Currently, I have incorporated an AJAX function in the shared master la ...