Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter highest numbers out of an object

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?

like image 907
user27074 Avatar asked Apr 13 '18 13:04

user27074


People also ask

How do you filter data in an object?

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.

How do you find the max value of an attribute in an array object?

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.


1 Answers

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);
like image 76
alex Avatar answered Sep 22 '22 05:09

alex