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 }
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 }
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 }
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:
n
(represented by a
initially) exists in the current "old" value (initially an empty object {}). If not, assign a count of 0
.o[n]
regardless.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.
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 ...
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 ...
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 ...
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, ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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_ ...
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 ...
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 ...
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 ...
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 ...
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 ...