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));
}
});
}