Tally up the occurrences of each item in the array and provide the result in the form

Is there a built-in method in JavaScript to convert an array like:

const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'];

into an object that counts the occurrences of each element, like this:

Object {
  "red": 3,
  "green": 2,
  "blue": 1,
  "purple": 1,
  "black": 1
}

I attempted to create a custom solution with a function, but I am wondering if there is a native method available for this purpose. Any insights would be greatly appreciated!

Answer №1

Array.prototype.reduce() appears to be the solution you've been searching for:

const colors = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'],

      results = colors.reduce((acc,color) => (acc[color]=(acc[color]||0)+1, acc), {})
      
console.log(results)
.as-console-wrapper{min-height:100%;}

Answer №2

Utilize the .reduce method:

const colors = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'];

let colorFrequency = colors.reduce((acc, curr) => ({ ...acc, [curr]: acc[curr] + 1 || 1}), {} );
      
console.log(colorFrequency);

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

Is there a way to retrieve the response body in Express framework?

In my NodeJS API using Express, I am attempting to save the response body of a request. To achieve this, I have created two middleware functions. app.use((req, res,next) => { res.status(404).json({ errors: [{ field: "url", ...

Access the value of a submitted form using jQuery, when there are multiple forms with identical class names

I've looked for a solution here but couldn't find one that meets my needs. I have multiple forms with the class name .sbt-form: <form class='sbt-form'> <input name='kord' val=1/> </form> <form class= ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

Building an HTML form to generate an array of objects by collecting form data

Hey there, I'm working on an HTML form in React that utilizes form action and FormData. However, when I extract the formData using my method, it shows a structure like this: https://i.stack.imgur.com/nzgLX.png My goal is to have an array of objects ...

Extract information from various files stored in Firestore

I have been struggling to retrieve data from multiple documents despite numerous attempts. The screenshot below displays that I have a collection of 3 documents, and my inquiry is how to extract data from each of them. https://i.stack.imgur.com/bFrIG.png ...

The custom attribute in jQuery does not seem to be functioning properly when used with the

I am currently working with a select type that includes custom attributes in the option tags. While I am able to retrieve the value, I am experiencing difficulty accessing the value of the custom attribute. Check out this Jsfiddle for reference: JSFIDDLE ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

There seems to be an issue with the functionality of the AJAX file upload feature in

I've developed a method for file uploading using AJAX technology (pure JavaScript) in CodeIgniter. Here's how it works: 1- I created a script.js file to manage the AJAX/JavaScript upload process. 2- I implemented a controller in CodeIgniter to ...

Tips for transferring information from a controller to a directive in AngularJS using AJAX requests

I want to pass data to a directive once the call is successful. Below is the ajax call from my controller: $scope.items ={ avatar: "" }; $scope.addComment = function(segment) { commentFactory.saveComment($scope.form.comment,segment,0, ...

Ensure to first close the existing global connection before attempting to establish a new one in your Node.js Post WebApi application

Currently, I am in the process of creating a small post WebAPI using node.js to collect user data such as names and numbers. However, when I have an excessive number of users accessing this web API, I encounter the following error message: "node.js Global ...

underscore.js does not allow data to be manipulated outside of the _.each

Struggling to get my head around utilizing the underscore loop in jQuery's $.ajax function for retrieving a JSONp file... Within the success section, I have the following code snippet: success : function(response) { var dataResp = '' ...

Implement a callback function to dynamically generate variables and display them within an HTML element

Apologies in advance for any errors I may make as I am a beginner when it comes to javascript, jquery, and json. I have a script that retrieves data from a json file and displays it on a webpage using javascript, jquery, ajax (I believe), and json. When ...

How can I hover over multiple cells in a table?

Is there a way to change the color of multiple adjacent cells when hovering over one cell, and can this be done dynamically (so the number of adjacent cells that change color can vary)? Here is the code snippet: I'm using React to create a table wit ...

Tips for enabling animation for AmCharts animateData feature

To achieve a real-time values per minute chart, the last bar value is to be incremented every minute after its addition. Additionally, a new bar with a value of 1 will be added each minute while removing the oldest bar. All these changes need to be animat ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

The process of inserting data using NextJS Mysql works seamlessly when executed through phpMyAdmin, however, it encounters issues when

My SQL query works perfectly in phpmyadmin, but I'm encountering an issue when making a request from the API. The API uses the MySQL package which was installed using: npm i mysql This is the SQL code that is causing the problem: BEGIN; INSERT INTO A ...

Trigger useEffect after prop has been changed

I'm trying to figure out how I can avoid running an API call in my component on initial rendering. The prop needed for the API call should be updated only after a form submission. Although I have included the prop in the dependency array of useEffect, ...

Creating a table in Javascript using an array of objects

I need a larger version of this data structure. [{ "votes":200, "invalid_votes":140, "valid_votes":60, "voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"} }, { "votes":300, "invalid_votes":40, "valid_votes":260, "voting_section":{"level":3, "zo ...

What are the steps to integrate HJSON with Jest in a create-react-app development environment?

Currently, I am utilizing HJSON within a create-react-app project (view answer here). However, Jest does not utilize the same webpack configuration, resulting in a failed import of HJSON - for instance, import options from '../assets/options.hjson&ap ...

What is the best way to incorporate CDN into my webpack build process?

I have developed a module with the following code: export default () => console.log('hello my_module~!') The configuration in the webpack.config.js file looks like this: module.exports = { // ... output: { // ... library: 'he ...