Utilizing JavaScript to fetch and render JSON data, implement a group sorting method to optimize data

I have some JSON data stored in a multi-dimensional array:

My goal is to retrieve the top 5 apdex scores by host and display them in a specific format similar to this:

So far, I've managed to find the top 5 apdex scores and sort them in descending order. I believe I need to implement a forEach function to loop through each host and display their respective apdex score and name. Unfortunately, I am not sure how to proceed with this task. Please refer to this fiddle for more details:

https://jsfiddle.net/marialaustsen/8uqafbs4/

fetch('https://marialaustsen.com/foo.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    appendData(data);
    console.log('data: ' + data);
  })
  .catch(function(err) {
    console.log('error: ' + err);
  });

Array.prototype.groupBy = function(prop) {
  return this.reduce(function(groups, item) {
    var val = item[prop]
    groups[val] = groups[val] || []
    groups[val].push(item)
    return groups
  }, {})
}

function appendData(data) {

  function getTopN(data, prop, n) {
    var clone = data.slice(0);
    clone.sort(function(x, y) {
      if (x[prop] == y[prop]) return 0;
      else if (parseInt(x[prop]) < parseInt(y[prop])) return 1;
      else return -1;
    });
    return clone.slice(0, n);
  }

  var n = 5;
  var topScorers = getTopN(data, "apdex", n);
  console.log("Top " + n + " apdex:");
  console.log('topScorers' + JSON.stringify(topScorers));

  topScorers.forEach(function(topScorer) {
    if (topScorer === 'host') {
      const groupedByHost = topScorer.groupBy('host')
      console.log('groupedByHost' + JSON.stringify(groupedByHost));
    }
  });

}

Answer №1

If you possess the necessary data and wish to display it on the DOM, follow these steps:


    var rootNode = document.querySelector('#root');
    var formattedData = data.map(item => {
        return ( 
            `<div>
            Name: ${item.name}
            <br />
            Contributors: ${item.contributors.map(cont => ` <span>${cont}</span>`)}
            <br />
            Host: ${item.host.map(ht => ` <span>${ht}</span>`)}
            <br />
            </div><br />`
        )
    });
    formattedData = formattedData.splice(',').join('');
    rootNode.innerHTML += formattedData;


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 is the process for creating a fade out effect with JavaScript?

https://i.sstatic.net/1qgWt.png Is there a way to create a fade out effect in JavaScript? In the image provided, you can see that when you click on a day, a box slides down. If you click on another day, the previous box slides back up while a new box slid ...

Guide on generating a unique X and Y rotation for every object created randomly in Three JS

I've been working on a personal project using Three JS as my main 3D object renderer. I'm trying to randomly generate spheres at various x, y, and z coordinates within a specified range. I was able to achieve this, but now I want each of these ob ...

Is it possible to manually input values when printing a PDF instead of pulling them from the main HTML?

I am facing a challenge in adding a "Print PDF" option to my website because it is built using Ext.js, and therefore the code is not in HTML. Despite searching for ways to print a PDF from the site, all solutions I found involve using HTML. Is there any li ...

Looking for an associative array that maintains identical keys for use in NuSoap?

To create a repeating array for this XML section, there is a challenge due to the presence of repeating items within the array structure. <orderItems> <OrderItemRequest> <line_id>int</line_id> <product_id>string< ...

The font size of the textarea dynamically adjusts based on the size of the screen

Some strange behavior is occurring in the Android default browser when I set the width and height of a textarea to 100%. The font size of the textarea seems to increase based on the screen size, and even though I attempted to alert the font-size using jQue ...

Every time I try to restart my React Project, it seems to encounter strange issues that

Currently, I am following a fullstack React tutorial which you can find here: React Tutorial I have encountered an issue where every time I close my laptop and reopen the project, npm start throws a strange error. Initially, I tried to fix it by starting ...

Discover the Closest Database Pointers on Google Maps Based on My Current Location

Currently, I am in the process of creating a feature where users can enter their postcode or address information and be presented with markers that are nearby. All of my markers are stored in a database. Initially, I planned to retrieve results from MySQL ...

Utilize NodeJS to iterate through a string and retrieve the precise results

Within my NodeJS project, I have a string in the following format: "Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?" The string ...

Emphasize a feature within a dynamic DIV

How can I highlight the span(class="tiny") element individually when its containing div is active or clicked? I have attempted to highlight the tiny span element without success, as only the entire div was highlighted. Here's the code snippet I' ...

What is the most efficient way to identify the factors of a number and store them in an array using C programming language?

#include<stdio.h> int main() { int num, counter, idx=0; char divisors[101]; printf("Please enter a number: "); scanf("%d", &num); for(counter=1;counter<=num;counter++) { if ...

What is causing the high value of scannedObjects in MongoDB even though all query fields are indexed?

My query is running slow while indexing three fields on a large collection, one of which is an array. Despite using the correct index, the number of scanned objects is high, resulting in poor performance with 300K fields. The exaggerated number of scanned ...

Guidelines for attaining seamless motion animation utilizing devicemotion rotationRate information

I am utilizing the rotationRate data obtained from the devicemotion eventListener to manipulate a three.js scene by tilting. The scene does respond to the data accurately in terms of angle adjustments, but it produces an unsmooth motion effect. Is there a ...

Error: The 'address' property cannot be found in the specified 'string' type

Hey there! I'm currently facing an issue while trying to pass an object from one page to another and store it in the object on the second page. I'm encountering an error with EsLint. let accountDetails:any={ name:this.userAccount.name, p ...

Obtain the string value of `reader.result` from the `FileReader

Struggling to retrieve a string in a reader.onloadend but it's constantly returning my entire function. Here is the function I'm using: uploadFile() { let vm = this; var file = vm.$refs["testeLogo"].files[0]; var reade ...

Use jQuery to compare the input values whenever they are modified

I am trying to synchronize the input values of two inputs as they are typed in. The code I have seems to work sometimes, but not consistently. Here is the code snippet: $('#google-querynav').keypress(function() { var text = $(this).val(); ...

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...

retrieve all JSON entries with more than x number of calls

Working with a json file containing 50 entries per page spread across multiple pages, I have a total of 500 entries split over 10 pages. My challenge lies in ensuring that the function waits for each page's data to be processed and added to an array ...

Display or conceal a div based on checkbox selection

I am trying to implement functionality to show/hide a div when a single checkbox is selected. Currently, it works with "Select all" but I am struggling to make it work with a single checkbox. Below is the code for "Select All": JS: <script language=&a ...

Efficient solution to transform a boolean array to a string: 'false, true, true, false'

Is there a concise way to convert an array of booleans into a string like "false, true, true, false" using minimal lines of code? In Python, it can be done elegantly with the following snippet: ", ".join(map(str, [False, True, True, False])) Unfortunate ...