What is the best way to find the frequency of a particular property's value in an array of key-value pairs?

Imagine we have an array filled with objects, where each object contains 3 key-value pairs.

const array = [                       // overall frequency/occurrence
  { id: 1, value_1: 2, value_2: 3 },  // 3 times value 3
  { id: 2, value_1: 3, value_2: 4 },  // 1 time  value 4
  { id: 3, value_1: 4, value_2: 3 },  // 3 times value 3
  { id: 4, value_1: 5, value_2: 2 },  // 2 times value 2
  { id: 5, value_1: 6, value_2: 3 },  // 3 times value 3
  { id: 6, value_1: 7, value_2: 2 },  // 2 times value 2
];

The task at hand is determining the current frequency count of each identical value_2 value within the entire array.

However, unlike the comments in the code snippet above, we need the output as an array where each element includes the current frequency count of its value_2 value, stored in an additional value_3 property ...

const array = [                       // expected:
  { id: 1, value_1: 2, value_2: 3 },  // value_3: 1 (1st occurrence of 3)
  { id: 2, value_1: 3, value_2: 4 },  // value_3: 1 (1st occurrence of 4)
  { id: 3, value_1: 4, value_2: 3 },  // value_3: 2 (2nd occurrence of 3)
  { id: 4, value_1: 5, value_2: 2 },  // value_3: 1 (1st occurrence of 2)
  { id: 5, value_1: 6, value_2: 3 },  // value_3: 3 (3rd occurrence of 3)
  { id: 6, value_1: 7, value_2: 2 },  // value_3: 2 (2nd occurrence of 2)
];

I managed to add value_3 as a new key in each object, but I'm struggling to iterate through the array to determine the current frequency count of value_2 for each item.

Answer №1

Utilizing a single reduce task allows for the computation of the result without changing the original array it is working with.

This is achieved by providing an object as the initial value to the reduce method's second argument. This object contains two entries: the counts object for grouped counts lookup and the result array, which serves as the final result array with each item having an additional value_3 property indicating its consecutive count-value.

During each iteration, a specific count entry for value_2 is either accessed or created. The value of value_2 acts as a key for the group specific counts. If the specific counter for value_2 does not exist yet, it is created and immediately set to zero.

let currentCount = (counts[key] ??= 0);

This is made possible by using the nullish coalescing assignment operator.

After incrementing the currentCount, it is assigned as an update to the specific counter for value_2. The only remaining task is to create a copy of the currently processed item with the additional value_3 property assigned the currentCount value.

The above approach can also be implemented to mutate the original array. This involves using forEach along with an anonymous function expression as the callback function to handle the counts object.

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

State of the Browser - JavaScript/jQuery

Looking for a method to identify when my browser is loading and display a loading icon. Is this approach appropriate, or should I follow a more common practice to achieve the same goal? Edit: This feature will be implemented on one of my websites during ...

Secure your Express.js session cookies for enhanced protection

Struggling to figure out how to set a secure cookie in the expressjs framework. Any suggestions on where I can find an option for this? ...

Generate nth-child selectors in a Material-UI component using props dynamically

I am currently working on customizing the Material UI slider component, specifically focusing on its marks prop to display the number of occurrences for each data object within the marks array. The desired appearance of the slider is illustrated in this i ...

Techniques for transferring child properties and values to parent components upon the screen being initialized

Is there a way to pass property values from a child component to a parent component when the react app is first loaded? In my scenario, I have a parent component named app.js that renders a home component containing a JSON component. Initially, upon loadi ...

Exploring PHP cURL with the power of jQuery

function php_download($Url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm"); curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); curl_setopt($ch, CURLOPT_H ...

How to retrieve multiple person or group values in SharePoint using JavaScript

Names from my SharePoint list are stored with the field names 'People' and 'Responsible', added using a peoplepicker. These fields are of type 'person or group' in SharePoint. In my Service file, I have the following code: ...

How can I retrieve the data property within the setup function in Vue 3?

Trying to access a data property inside setup() in Vue 3 is resulting in the following error: TypeError: Cannot read property '$localStorage' of undefined data() data() { return { $localStorage: {}, } setup setup() { this.$loca ...

Combining Socket.io with AJAX for real-time web applications

I am currently working on a web application that relies on Socket.io for delivering notifications to users. I'm wondering if it would be more beneficial to utilize Socket.io exclusively for all client-server communication, or if mixing in traditional ...

Does Internet Explorer 10 support the FormData object?

I've developed a JavaScript app that enables me to upload images asynchronously, and it works seamlessly in most browsers. However, the infamous Internet Explorer is causing some trouble... To address this issue, I devised a workaround for IE9- versi ...

Tips for handling the response after a view has been submitted on Slack using Bolt.js

Hey there! I added a simple shortcut to retrieve data from an input, but I'm facing an issue after submitting the view. The response payload is not received and the view doesn't update to give feedback to the user. Check out my code below: const ...

Tips for testing parallel, mocked data requests in JEST by simulating cached responses with a 500ms limit

In order to simulate parallel requests fetching data from different sources, I have implemented tests that introduce artificial latency for each request. The goal is to return a simple string with an identifying digit to determine whether the data has been ...

Combining multiple arrays in PHP to create a unique merged array

I have been developing a unique tool that merges arrays containing attributes together. However, I am facing a challenge in achieving this goal. My approach begins with decoding JSON data into arrays using the following code: $input = '{"1" ...

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

Attempted to execute my testing script with mocha, however encountered a "Reference Error: beforeEach is not defined" issue

While running my test script for a todo app in node.js using Mocha, I encountered a reference error stating that "beforeEach is not defined". The code snippet causing the issue is shown below: const {app} = require('./../server'); const {Todo} ...

Enhancing jQuery's ScrollTop Functionality

My jQuery script for scrolling to the top of a container seems to accelerate after it starts. It begins slowly and then speeds up. Is there a way to prevent this lag at the beginning and maintain a consistent speed throughout the entire scroll? // Once t ...

Maximizing the potential of AFRAME animations: Tips for recycling your animations

Looking to create a unique and irregular animation, similar to the pattern of a waterdrop falling: Drip nothing Drip Drip Drip nothing nothing Is there a method to achieve this effect or loop an extended animation sequence of dripping? ...

"Put Phonegap on hold for a bit and disable landscape mode

I am currently using Phonegap to develop an Android game. My project includes a lobby feature where players can search for opponents and engage in chat with other players. Once a player has found their opponent, they can commence playing the game together ...

AngularJS and PHP - Issue with HTML tags not being decoded properly

I'm currently working on a project using angularJS with a PHP backend and MySQL database. The PHP API is responsible for sending data to the angularJS frontend for display. Unfortunately, I'm facing an issue where HTML tags are not being decoded ...

Replicate and modify the settings on a fresh radio inspection

In my approach, I am avoiding direct HTML editing and instead utilizing JavaScript/jQuery to accomplish the desired outcome. Initially, one input (specifically 'Express Shipping') is pre-selected by default. The goal is to clone/copy the HTML co ...

Adding hidden elements with jQuery: A comprehensive guide

I need assistance with adding the "is-hidden" class at this specific spot <span class="tag is-danger is-rounded is-small is-bolded span_notif_count ... "></span> As a beginner in jQuery, I am unsure about how to proceed. Could someon ...