JavaScript Simplified Data Sorting after Reduction

I have extracted data from a JSON file and successfully condensed it to show the number of occurrences. Now, my next step is to arrange these occurrences in descending order, starting with the most frequent. To illustrate:

var myData = [{
        "datapoint1": "55",
        "datapoint2": "500",
        "datapoint3": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="177a6e7376637657737663763974787a">[email protected]</a>",
        "datapoint4": 5656
    }, {
        "datapoint1": "55",
        "datapoint2": "404",
        "datapoint3": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5835213c392c396a183c392c39763b3735">[email protected]</a>",
        "datapoint4": 5656
    }, {
        "datapoint1": "55",
        "datapoint2": "502",
        "datapoint3": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cca1b5a8adb8adff8ca8adb8ade2afa3a1">[email protected]</a>",
        "datapoint4": 5656324
    }, {
        "datapoint1": "55",
        "datapoint2": "500",
        "datapoint3": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660b1f02071207555526020712074805090b">[email protected]</a>",
        "datapoint4": 5656554
    }
]

After parsing the JSON data, mapping the entries, and reducing them based on datapoint 2 occurrence, I now possess the frequency count for each datapoint. For simplicity's sake, the sample dataset above is repeated numerous times.

var dataParsed = JSON.parse(myData);
var mapDataPoint2 = dataParsed.map(function (data) {
return data.datapoint2
});

var reduceDatapoint2 = mapDataPoint2.reduce(function (prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});

console.log(reduceDatapoint2)

Although I can successfully display the occurrence counts via console log, my struggle lies in organizing this data from highest to lowest frequency. My attempts with .sort() method are fruitless, as no errors surface in the console output.

I would greatly appreciate any guidance or assistance on tackling this issue.

Answer №1

To organize the values, utilize the information obtained from reduceDatapoint2:

myData.sort((a,b) => reduceDatapoint2[b.datapoint2] - reduceDatapoint2[a.datapoint2]);

DEMO

var myData = [{
    "datapoint1": "55",
    "datapoint2": "500",
    "datapoint3": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45283c2124312405212431246b262a28">[email protected]</a>",
    "datapoint4": 5656
  },
  {
    "datapoint1": "55",
    "datapoint2": "404",
    "datapoint3": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb0a4b9bca9bcef9db9bca9bcf3beb2b0">[email protected]</a>",
    "datapoint4": 5656
  },
  {
    "datapoint1": "55",
    "datapoint2": "502",
    "datapoint3": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e28f9b86839683d1a286839683cc818d8f">[email protected]</a>",
    "datapoint4": 5656324
  },
  {
    "datapoint1": "55",
    "datapoint2": "500",
    "datapoint3": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="24495d40455045171764404550450a474b49">[email protected]</a>",
    "datapoint4": 5656554
  }
]

var dataParsed = myData;
var mapDataPoint2 = dataParsed.map(function(data) {
  return data.datapoint2
});

var reduceDatapoint2 = mapDataPoint2.reduce(function(prev, cur) {
  prev[cur] = (prev[cur] || 0) + 1;
  return prev;
}, {});

console.log(reduceDatapoint2)

myData.sort((a, b) => reduceDatapoint2[b.datapoint2] - reduceDatapoint2[a.datapoint2]);
console.log(myData);

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

If an iframe contains a div with a particular class inside, then execute the following code

I need to dynamically add a class to the parent element if a specific class is present in its child. The issue: the content is within an iFrame and I'm not very proficient with jQuery. It doesn't necessarily have to be jQuery, any alternative m ...

What is the best way to remove a specific item from a list of maps in DynamoDB based on a particular attribute value within the

Below is an example of a list I have: { "favorites": [ { "createdAt": 1448998673852, "entityId": "558da3de395b1aee2d6b7d2b", "type": "media" }, { "createdAt": 1448998789252, "entityId": "558da3de395b1aee2d6b7d83 ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Utilizing Vue and Websockets for seamless communication: Managing the exchange of messages between users

In an attempt to create a messaging system that shows alerts of messages to different users, I have implemented Vue Socket Io from https://www.npmjs.com/package/vue-socket.io. However, the issue lies in the fact that the alerts are not being triggered as e ...

What is the speed of communication for Web Worker messages?

One thing I've been pondering is whether transmission to or from a web worker could potentially create a bottleneck. Should we send messages every time an event is triggered, or should we be mindful and try to minimize communication between the two? ...

Attempting to cycle through a collection of dictionary elements

I have a JSON list containing ServerIPList with PrivateIP values that I want to iterate through and append to the empty InstanceIds list: Here's the code snippet: InstanceId = [] message = [{"SNowTicket":"RITM00001","ServerIP ...

Resetting several sticky titles after displaying and hiding elements

Inspired by a popular codepen example, I have successfully implemented sticky titles in my sidebar. However, when integrating these sticky titles with the functionality to show/hide related items on click, I encountered some unexpected issues. The code sni ...

When the collapse button is clicked, I aim to increase the top value by 100. Subsequently, upon a second click, the top value should

https://i.stack.imgur.com/p9owU.jpghttps://i.stack.imgur.com/Kwtnh.jpg I attempted to utilize jQuery toggle, but unfortunately, it is not functioning as expected. <script> $(document).ready(function () { $(".sidebar ul li&quo ...

Error: The term "Image" is unrecognizable

I'm in the process of creating a website where I want to display images via links. If the image is missing or only 1 pixel wide, I need the site to show an alternative image. My technology stack includes Jade/Pug and JS. Before rendering the links on ...

The toLowerCase method seems to be malfunctioning along with several other functions

JS var score = 0 var yes = "yes" var pokemonName = []; var bg = []; var index = 0; document.getElementById('repete').style.visibility = 'hidden'; (function asyncLoop() { background = bg[num = Math.floor(Math.random() ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Zero's JSON Journey

When I make an HTTP request to a JSON server and store the value in a variable, using console.log() displays all the information from the JSON. However, when I try to use interpolation to display this information in the template, it throws the following er ...

Unable to process login information with form method post on basic login page

Hi, I've been struggling with a simple login page issue. It works fine with Bootstrap, but I want to switch to Angular Material Design. I've been searching for the problem for about 3-4 hours and can't find anything. I suspect that the form ...

Creating an Ajax request in Angular using ES6 and Babel JS

I have been exploring a framework called angular-webpack-seed, which includes webpack and ES2016. I am trying to make a simple AJAX call using Angular in the traditional way, but for some reason, it is not working. export default class HomeController { ...

Unable to modify the styles of nested Material UI components

I am currently customizing the styles of the card and cardContent components in material ui. I have implemented them within functional components and am facing an issue with overriding the root style of each component. Specifically, I am struggling to modi ...

How can I effectively save data to a session using connect-redis?

I am looking to save the username of an account into session storage. I am currently using node.js with the expressjs framework and have attempted to utilize connect-redis for storing sessions, following a tutorial on expressjs. Can someone please guide ...

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

When trying to run ionic serve, I encountered the following error: "[ERROR] ng has unexpectedly closed with an exit code of 127."

My attempt to launch an ionic app on my Mac has hit a roadblock. While running npm install for the dependencies, everything goes smoothly without any issues. However, when I try to run 'ionic serve' or 'ionic s', an error crops up: [ng] ...