JavaScript transforming an array into a counter

I am seeking a way to transform a one-dimensional array into a frequency dictionary in JavaScript. The array elements should serve as keys, while their frequencies act as values.

Take, for example, the Python script below, which generate a list of 1024 random numbers ranging from 0 to 255, and then count their occurrences:

import random
from collections import Counter

sorted(Counter(random.randbytes(1024)).items(), key=lambda x: -x[1])

I can achieve the same in JavaScript, albeit not as succinctly:

var numbers = Array.from({length: 1024}, () => Math.floor(Math.random() * 256))
var counter = Object()

for (let number of numbers) {
    if (counter.hasOwnProperty(number)) {counter[number] += 1}
    else {counter[number] = 1}
}

Object.entries(counter).sort(([,a],[,b]) => b-a)

Is there an easier way to accomplish this task more concisely?

Answer №1

This particular test result caught me off guard: when running tests with 100 million numbers on my Mac, the Map version took 2.7s, whereas the Object version only took 0.6s.

(Interestingly, the original version performs the same as the Object version in the code snippet below)

const numbers = Array.from({length:10**8},()=>Math.random()*256|0)

let timerStart = new Date()
{
  let counter = new Map()
  numbers.forEach(n=>counter.set(n,(counter.get(n)??0)+1))
  counter = new Map([...counter].sort(([,a],[,b]) => b-a))
}

console.log(`Map version took ${new Date()-timerStart} ms`)

timerStart = new Date()
{
  let counter = numbers.reduce((a,c)=>(a[c]=(a[c]??0)+1,a),{})
  Object.entries(counter).sort(([,a],[,b]) => b-a)
}

console.log(`Object version took ${new Date()-timerStart} ms`)

Answer №2

Check out this efficient ES6 solution using Array.reduce and the comma operator for a one-liner code snippet:

const numbers = Array.from({length: 1024}, () => Math.floor(Math.random() * 256))

const counter = numbers.reduce((acc, num) => (acc[num] = (acc[num] || 0) + 1, acc), {})

const sorted = Object.entries(counter).sort(([,a],[,b]) => b-a)

console.log(sorted)

Answer №3

If you're looking to implement a more efficient solution, consider utilizing a Map data structure:

const items = Array.from({length: 1000}, () => Math.floor(Math.random() * 200))

const mappedItems = items.reduce((accum, item) => accum.set(item, (accum.get(item) || 0) + 1), new Map());

Answer №4

An easy way to enhance the code's readability is by utilizing the ternary operator for a more concise expression.

const numbers = Array.from({length: 1024}, () => Math.floor(Math.random() * 256));
const counter = Object();

for (let number of numbers) {
    counter[number] = counter.hasOwnProperty(number) ? counter[number] + 1 : 1;
}

Object.entries(counter).sort(([,a],[,b]) => b-a);

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

What possible reason is causing ag grid to overlook the defaultExcelExportParams option that was provided?

Here is my React ag grid code snippet. I'm trying to implement the processCellCallback function, but unfortunately, I am not seeing the console.log output in the browser console when exporting excel. Any suggestions on what might be causing this issue ...

In jQuery, apart from utilizing class, id, and text properties, what other methods can be used to pass a variable within an element?

Currently, I am facing a scenario where the class and id attributes are already assigned, but I need to pass a variable to jQuery. How should I go about this? Here is the HTML code: <input type="text" id="cannot_change_this" class="rather_ ...

Click to Rotate the Shape

I am attempting to apply a rotation effect on a shape when clicked using jQuery and CSS. My goal is to select the element with the id of x and toggle the class rotate on and off. The rotate class utilizes the CSS transform property to achieve the desired r ...

Exploring the power of loops in manipulating arrays

I need assistance in optimizing the expressions using a for loop to achieve cleaner code. This task needs to be repeated four times for u1, u2, v1, and v2 while storing these arrays each time. delta_u1_up_down = [] delta_u1_first = [] delta_u1_previous = [ ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

Error in Node.js: Unhandled promise rejection due to undefined value

We're currently facing an issue with the create user controller in Node.js Express. The problem arises when attempting to sign up on the front end, resulting in an error message: "Unhandled promise rejection error value is not defined." Although it ap ...

What is the best way to capture videos using Safari?

Hey there! I've set up the browser camera on my website for users to record live tests. It's been working great on Chrome and Firefox using MediaRecorder, but unfortunately, Safari isn't cooperating. Does anyone know of an alternative to Me ...

What is the correct way to integrate the Ant Design library with Next.js for seamless server-side rendering?

I duplicated the official Next.js example using Ant Design at this link: https://github.com/vercel/next.js/tree/canary/examples/with-ant-design After cloning, I proceeded with npm install to install all dependencies. Then, I ran npm run dev to check if ev ...

Ways to create a shorter upper line compared to the lower line (inside a div)

I'm dealing with an unordered list that has 3 list items, each represented by a green box containing an image and 3 divs (title, location, price). My main focus is on the title div of each box. If the title is long enough to span 2 lines, I need the ...

Oops, it seems like there is a TypeError with the function window.initMap in Google Maps

For the past week, I have been struggling to update my marks on Google Maps while using AJAX in an HTML page. My controller fetches data from the database and sends it back, but now I am encountering the following error: TypeError: window.initMap is not a ...

Utilize Node.js and an API to generate a new problem in GitHub, but encountering an issue where the response

I have been experiencing an issue related to making a Post request to the Github API for creating an issue. I have gone through this post on Stack Overflow but I am seeking assistance in using the request module. Although I have referred to the Github docu ...

I aim to display interconnected information from various APIs in a cohesive manner

I am working with two APIs: component.ts ngOnInit(): void { this.getQueryCountriesList().subscribe(arg => { this.countryDatas = arg; }); this.getQueryNights().subscribe(obj => { this.nightDatas = obj; }); ...

Having trouble with table sorting in Jquery?

I am a beginner in the realm of Jquery and web programming. Recently, I attempted to implement the tablesorter jquery plugin for one of my projects but encountered issues with making it work properly. In search of a solution, I turned to Stack Overflow. C ...

Google charts appear only after the second request, not on the initial one

Utilizing Google charts to visually represent company performance data. The Javascript code I have written is as follows: <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> go ...

Updating props in a recursive Vue 3 component proves to be a challenging task

I am facing an issue with two recursive components. The first component acts as a wrapper for the elements, while the second component represents the individual element. Wrapper Component <template> <div class="filter-tree"> &l ...

Implementing pagination within nested ng-repeat in Angular app

I am currently utilizing Angular along with the Material library in my project. I am facing an issue with two nested ng-repeat loops within md-tables. The problem lies in the fact that the variable is getting overridden with each request in the nested loop ...

Enhance efficiency of repetitive tasks involving accessing the Mongo database

Currently, I am developing a chat bot using MeteorJS/NodeJS, which engages with approximately 2,000 active users on a daily basis. Tracking the number of individuals who interact with the bot each day is made possible by storing their activity information ...

Trouble with AJAX communicating with PHP and not rendering fresh data

I have created a row of images that are clickable, and once clicked, a variable is sent via AJAX to a PHP file for a database query. The PHP file receives the variable and executes the correct query. However, instead of updating the HTML on my page, it sim ...

ngInfiniteScroll Activates on Every Scroll Occurrence

Implementing ngInfiniteScroll for endless scrolling on my website has required me to set the height of the outer div to a specific value. Without this adjustment, the Infinite Scroll feature activates unintentionally. <div style="height: 1px"> &l ...

Custom validation on the client side using ASP.NET and JavaScript WebMethods

I am encountering an issue with client-side validation using a JavaScript function. On my ASP.NET C# page, I have a WebMethod that successfully validates data entered by the user. The page includes a textbox with an AJAX AutoCompleteExtender, which is work ...