I have the following object, with points per sport for an individual person. This information comes out of a database, based on the search for "Jack Miller"
Jdata = {
"name": "Jack Miller",
"sports": {
"Basketball": 2,
"Football": 3,
"Iceskating": 5,
"Running": 4,
}
}
I would like to display the top 2(3) sports for the name on my HTML page. Do to that, I was thinking to extract the information into an array like this:
SportVal = [];
SportNames = [];
for(var key in this.Jdata.sports){
if(!this.Jdata.sports.hasOwnProperty(key)){
continue;
}
this.SportVal.push(this.Jdata.scores[key]);
this.SportNames.push(key)
}
Then I would have to sort the SportVal array in descending order and can use e.g. ngFor in the HTML to display the results.
However, how would I get back the corresponding Names? Also I don't think this is the most effective way, since I run into a problem if scores are equal. So do you maybe have a better idea how to do this?
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
Maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method is by using the Math. max. apply() method.
You could use Array.prototype.sort()
to do it.
Jdata = {
"name": "Jack Miller",
"sports": {
"Basketball": 2,
"Football": 3,
"Iceskating": 5,
"Running": 4,
}
}
const sorted = Object.entries(Jdata.sports)
.sort((a, b) => b[1] - a[1])
.slice(0, 3)
.map((pair) => pair[0]);
console.log(sorted);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With