Angular 2: Finding the object with the highest attribute value in an array of objects

I am currently developing an Angular 2 application and I have an array of objects. My goal is to return the object that has the maximum value of a specific attribute (in this case, the object with the most likes). How can I achieve this in TypeScript?

import {Player} from './player';
export const PlayersData : Player[] = [
{id:1,name:"Marc-andré Ter stegen",number:"1",post:"Goalkeeper",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/150720.jpg"},
{id:2,name:"Gerrad Piqué",number:"3",post:"Defender",goals:0,assist:0,likes:10,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/27798.jpg"},
{id:3,name:"Ivan Rakitić",number:"4",post:"Midfielder",goals:0,assist:0,likes:7,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/35308.jpg"},

... additional player data ...

{id:14,name:"Samuel Umtiti",number:"23",post:"Defender",goals:0,assist:0,likes:9,dislike:0,img:"http://s.weltsport.net/bilder/spieler/gross/170711.jpg"}

];

This is my TypeScript attempt:

export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
  constructor(private playerService : PlayerService) { }
 max = 0;
 bestPlayer = this.players[0];
  ngOnInit() {
    this.playerService.getPlayers()
      .then(players => this.players = players);
    for (player of players)
        if (player.likes > max) {
          max => player.likes;
          bestPlayer => player;
        }
  }

}

Answer №1

Just like Igor advised, it's important to review the duplicate topic first before proceeding further. I also recommend exploring the suggestion to extract an object containing the maximum value for your other query. For a more comprehensive solution, please refer to this helpful discussion Example Topic

export class DashboardComponent implements OnInit {
  players : Player[] = [];
  bestPlayer:Player;

  constructor(private playerService : PlayerService) { }

  max =0;

  ngOnInit() {
    this.playerService.getPlayers()
    .then(players=> {
         this.players = players;
         let maxValue = Math.max.apply(Math,players.map(function(o){return o.likes;}));
         this.bestPlayer = players.filter(function(o) { return o.likes === maxValue; })[0];
     });    
  }
}

Answer №2

If you're looking for a reliable solution, I recommend utilizing the Lodash library. Lodash offers a convenient maxBy function that can analyze an array of objects and identify the one with the highest value based on a specific property.

Take a look at this example provided on their website:

var objects = [{ 'n': 1 }, { 'n': 2 }];

_.maxBy(objects, function(o) { return o.n; });
// => { 'n': 2 }

// You can also use the shorthand notation with `_.property`.
_.maxBy(objects, 'n');
// => { 'n': 2 }

Answer №3

After some searching, I finally figured it out:

topPlayer:Player;
entries:Player[];
highestLikes:number = 0;
constructor(private playerService : PlayerService) { }
ngOnInit() { 
    this.entries = this.playerService.fetchEntries();
    for (var i = 0; i < this.entries.length; i++) {
        if (this.entries[i].likes > this.highestLikes) {
            this.highestLikes = this.entries[i].likes;
            this.topPlayer = this.entries[i];
        } 
    }

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

Adjust the column width in Angular material tables

Is it possible to adjust the width of individual columns? I've attempted various methods, but it appears that the columns are consistently equal in width regardless of any styles applied. ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

Leveraging foreign key attributes within Angular templates

My technology stack includes Django for the backend with Django Rest Framework and Angular for the frontend. Within the backend, I have defined 2 models: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null= ...

Tips for displaying an object's properties using ngfor?

<div *ngFor="let article of articleList; let i = index"> <div class="item"> <div class="image-holder" style="background-image: url(https://uniqueblog.com/images/ninja-1.jpg)"&g ...

Invoke a function within an Angular component that is passed in as a parameter

Is it possible to invoke a function using a string in JavaScript? I have a scenario where I receive a string as the function name, and I need to call and run that function. However, my current code is not working as expected. Below is the code snippet I ...

Avoid selecting primary key column in TypeORM查询

Is it possible to exclude primary key columns from being selected in TypeORM? I've tried using the select false option, but it doesn't seem to work for these specific columns. Could it be because they are essential for identifying the entity or b ...

Navigation problem in Angular: Page remains unchanged despite URL updating

I am experiencing an issue with two components, home and welcome. The welcome component contains a button that, when clicked, is supposed to take me to the 'home' page. However, instead of navigating to the home page and displaying its content, i ...

Protected class, yet not transferable

My output varies based on the type of input provided. I have a custom guard in place to protect the input, but I'm still having trouble assigning it to the declared output: type InputType<Sub extends SubType> = { a: Sub, b: string } type SubTyp ...

Utilize the key types of an object to validate the type of a specified value within the object

I am currently working with an object that contains keys as strings and values as strings. Here is an example of how it looks: const colors = { red: '#ff0000', green: '#00ff00', blue: '#0000ff', } Next, I define a type ...

What is the best way to configure webpack for ng build instead of ng serve?

My .NET web application is hosted in IIS and it also hosts an Angular application. This setup requires both applications to be served on the same port by IIS, primarily because they share the same session cookie. Additionally, they are integral parts of th ...

Showcasing a recently incorporated mat-card

I have a collection of mat-cards that are being displayed using data received through an observable called cars$. Each time a new car object is emitted by this observable, a new mat-card appears automatically. Is there a way to make the newly added mat-c ...

Testing TaskEither from fp-ts using jest: A comprehensive guide

Entering the world of fp-ts, I encounter a function (path: string) => TaskEither<Erorr, T> that reads and parses configuration data. Now, my challenge is to create a test for this process. Here is what I have tried so far: test('Read config& ...

New behavior in Vue 3: defineEmits is causing issues with defineProps data

Currently, I am working with Vue 3 and TS 4.4. In one of my components, I am using defineProps to define prop types. However, when I try to add defineEmits, VS Code starts indicating that my props variable is not recognized in the component template. Below ...

Tips on inferring a distinct generic type for every element within an array of objects

I'm working on code that creates a timeline chart for data. I want the code to accept an array of series, each containing data and various getters used to position and render the data on the chart. Below is a simplified example of the code. The actua ...

Encountered an issue: Unable to access the property 'querySelectorAll' of null and Unable to access the property 'getElementsByTagName' of null

*<div class="col-md-12" *ngIf="data_client2.length>0"> <button class="btn print" printSectionId="listVotantesPrint" ngxPrint i18n="@@downloadList"></button> ' <button class=&qu ...

Utilizing SVG Images on Buttons within Material Design (MD-Icon)

I have experimented with different methods, but none seem to be effective: <button md-icon-button color="primary"> <md-icon md-svg-src="./assets/img/sprites.svg">menu</md-icon> </button> and also tried this: <md-icon svgSrc= ...

Trouble arises when extending an MUI component due to a TypeScript error indicating a missing 'css' property

We have enhanced the SnackbarContent component by creating our own custom one called MySnackbarContent: export interface MySnackbarContentProps extends Omit<SnackbarContentProps, 'variant'> { variant?: MyCustomVariant; type?: MyCustomTy ...

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

C++ server supporting HTTP communication paired with Angular using Typescript on the client-side

Currently, I am diving into an AngularCLI project using TypeScript and admittedly, I am still a novice in this realm. The specific requirements of the project involve updating a client-side image every 70 milliseconds along with some camera configurations. ...