Determine the occurrences of each element in a given array and save them as key-value pairs

Is there a way to efficiently convert an array of elements into an object with key value pairs representing element frequencies? For example, given an array:

     var array = ['a','a','a','b','b','c','d','d','d','d',] 

I want to transform it into an object like this:

     obj = [{ element: 'a', frequency: 3}, 
            { element: 'b', frequency: 2},
            { element: 'c', frequency: 1},
            { element: 'd', frequency: 4}]

Instead of the above format, I currently have a solution that provides the following output:

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

Answer №1

If you want to transform it, you can utilize the Object.entries method as demonstrated below.

const myObj = {
  x: 5,
  y: 7,
  z: 2,
  w: 9
};

const result = Object.entries(myObj).map(item => ({
  key: item[0],
  value: item[1]
}));
console.log(result);

Answer №2

If you want to manipulate an object using JavaScript, consider using Array#map in conjunction with Object.entries and destructuring.

const obj = { x : 5, y : 6, z : 7, w : 8 };
const result = Object.entries(obj).map(([key, value])=>({key, value}));
console.log(result);

Answer №3

Utilizing a map for easy and quick access while calculating the frequencies is a clever approach, but have you ever considered generating the desired objects directly?

For example, instead of:

{ a: 3
, b: 2
}

Why not try this instead?

{ a: {element: 'a', frequency: 3}
, b: {element: 'b', frequency: 2}
}

By doing so, you can simply use Object.values(obj) to achieve your desired outcome.


const freq =
  xs =>
    Object.values
      ( xs.reduce
          ( (acc, x) =>
              ( acc[x] = acc[x] || {element: x, frequency: 0}
              , acc[x].frequency += 1
              , acc
              )
          , {}
          )
      );
      
      
console.log(freq(['a','a','a','b','b','c','d','d','d','d']));

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

A problem arises in Next.js when CSS is not rendering properly during Server Side Rendering

After creating my next.js application using the command npx create-next-app, I realized that the styles from the imported .css files are rendering correctly on Client Side Render but not on Server Side Render. The Next.js documentation states that importe ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

Unable to adjust the width of the react-select component

I've been struggling to adjust the width of the select element but no matter what I try, it remains at a default width of about 75px. const CustomContainer = styled('div')` width: 100%; height: 100%; display: flex; flex-flow: row wr ...

Encountering challenges with concealing a div element

As I'm setting up a table, I want to hide it immediately after creating it without affecting the DOM. Then, when the user selects from a dropdown menu, I show the table and everything works fine. However, the issue arises when I visit the page for the ...

javascript tabs not functioning as expected in HTML

I am currently putting the finishing touches on a basic website for a project I'm involved in. The site features two tab controls - one on the right side of the page and the other on the left. Each control has 3 tabs that, when clicked, display differ ...

PHP fails to retrieve posted data from AJAX when using serializeArray()

I have been struggling with a form that is utilizing jQuery validation and AJAX to submit data to a PHP script for backend processing. The AJAX function uses serializeArray() to collect the form values, but despite my best efforts, I cannot seem to success ...

javascript: verify the presence of uppercase and lowercase letters

Can the validation of at least 2 lowercase and 2 uppercase letters be implemented when checking the case? Below is the condition I am currently using. function HasMixedCase(passwd){ if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) return true ...

Create a loop in JavaScript to iterate through elements using both a while loop and the

I have a JSON object (returned by the server) and I am looking to iterate through it with either a while loop or forEach method in order to display the products in a shopping cart. The name of my object is response2, which contains the cart products. I w ...

Differences between the application/xml and text/xml MIME types

How can I receive an XML response from a servlet? The servlet returns a content type of "application/xml". When using XmlHttpRequest, I am able to get responseText, but not responseXml. Could this be related to the content type or the request type (I' ...

Is there a way to extract the unicode/hex representation of a symbol from HTML using JavaScript or jQuery?

Imagine you have an element like this... <math xmlns="http://www.w3.org/1998/Math/MathML"> <mo class="symbol">α</mo> </math> Is there a method to retrieve the Unicode/hex value of alpha α, which is &#x03B1, using JavaScrip ...

What is the best way to stack col-xs-6 elements instead of having them side by side?

My form fields are currently set up using 3 col-xs-6 classes, but I'm not seeing the desired layout. I am aiming for: | col-xs-6 | | col-xs-6 | | col-xs-6 | However, what I am getting is: | col-xs-6 | col-xs-6 | | col-xs-6 | I understand that th ...

.Certain IDs on a website may not respond to clicks due to various reasons

I have created a JavaScript file to automatically click a button on a website using a Chrome extension. When testing the code using Chrome Script snippet, I noticed that it worked for some IDs but not for others. Can someone please help me with this issue? ...

Unable to locate module - relative file path

I'm currently running a test with the following code and encountering an error message: Failed: cannot find module '../page/home_page.js The main page consists of: describe("login to website",function(){ var employeeId; var employee ...

What exactly does a 'hoisted manifest' mean when it comes to using Yarn?

Encountering an issue while attempting to install a package using yarn, I am receiving the error message: expected hoisted manifest for \"myPackage#@material-ui/core#react-dom\" However, the concept of a 'hoisted manifest' is not entir ...

Encountering an issue with Angular's absence while attempting to minify the files

I utilized grunt along with usemin to merge and compress the following code: <!-- build:js /assets/vendor.js --> <script src="../public/bower_components/angular/angular.min.js"></script> <script src="../public/bower_components/angular ...

Is it feasible to generate a fixed lighting effect overlay with HTML and CSS?

Is it possible to incorporate a static lighting effect overlay using HTML/CSS? My project consists of an HTML5/JS app with a top navigation bar and a series of cards that are transitioned through using swipe gestures. These cards are displayed in gray ove ...

Exploring the world of animation in the upcoming Next.js 13

I need assistance with converting this code into Next.js 13. My goal is to implement a page animation using Framermotion, but I'm having trouble understanding how to do it in Next 13. // _app.js import { AnimatePresence } from 'framer-motion ...

Is there a way to have dynamic content from angularJS show up in an iframe?

When working with tabular content generated using ng-repeat in AngularJS, it is important to find a way to display this content within an iframe. The goal is to allow users to drag and resize the content as needed. However, using the iframe src attribute ...

Utilizing KnockoutJS to Apply CSS Binding Based on Dropdown Selection

Check out the live example here: http://jsfiddle.net/0gmbbv5w/ In my application, I have an object retrieved from the database that I bind to a <select> var NoticeType = function (noticeType) { this.NoticeTypeId = ko.observable(noticeType.Notic ...

What's the process for setting a value in selectize.js using Angular programmatically?

Currently, I am implementing the AngularJS directive to utilize selectize.js from this source: https://github.com/kbanman/selectize-ng In my scenario, I have two dropdowns and my goal is to dynamically populate one of them called selectizeVat based on the ...