Find the maximum value in an array using TypeScript

I have a single-column array called n_fnc and I am trying to find the maximum value within it. However, my current approach does not seem to be working.

 let first = this.fncs.map(item => item.n_fnc);
   console.log("First",first);
    x= Math.max(...first);

[

fnc service

getlastid(response,fncs:Fnc[]):void{
      let fnc:Fnc;
      response.forEach(element => {
        
        fnc =new Fnc();
        fnc.n_fnc=element.n_fnc;
        fncs.push(fnc);

    });

Fnc component.ts

this.fncs=[];
this.fncservice.obs.subscribe((response)=>this.fncservice.getlastid(response,this.fncs));
     console.log("A",this.fncs);
    var max= Math.max.apply(Math, this.fncs.map((m) => m.n_fnc));
    console.log("Max",max);

Answer №1

If you want to achieve this, you can utilize the apply function as shown below:

var numbers = [{
 n: 1
},{
 n: 499
},{
 n: 99
},{
 n: 10
}];

var maximum = Math.max.apply(Math, numbers.map((num) => num.n));
console.log(maximum);

The code snippet within fnc.component.ts needs to be implemented like so:

this.numbers=[];
this.numberService.observable.subscribe((data)=> {        
    this.numberService.findMax(data, this.numbers);
    console.log("A", this.numbers);
    var maxNum = Math.max.apply(Math, this.numbers.map((num) => num.n));
    console.log("Max Num", maxNum);
});

Answer №2

If you want to accomplish this task, you can make use of the apply function as shown below:

let functions = [{
 n_function: 5
},{
 n_function: 30
},{
 n_function: 15
},{
 n_function: 8
}];

let sortedFunctions = functions.sort((a, b) =>  { return b.n_function > a.n_function ? 1 : -1; });

console.log(sortedFunctions[0]);

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

Encountering TypeScript Error when Using Hooks (possible type mismatch?)

Currently, I am developing a custom `useProject` hook in TypeScript that is utilizing a function defined in `useProjectFunctions.ts`. While working on the `useProject` hook, I encountered a TypeScript error indicating type mismatch, although I am unable t ...

Angular 4: Transform a string into an array containing multiple objects

Recently, I received an API response that looks like this: { "status": "success", "code": 0, "message": "version list", "payload" : "[{\"code\":\"AB\",\"short\":\"AB\",\"name\":\"Alberta&b ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Running ngAfterViewInit() code in Angular should be done only after Inputs() have been initialized

Within a particular component, I have implemented some code in ngAfterViewInit: @Input public stringArray: string[]; public newArray: string[]; ngAfterViewInit() { this.newArray = this.stringArray.filter(x => x.includes('a')); } I placed ...

Refresh a doughnut chart in real-time using NG2Charts

Currently, I am in the process of developing a macronutrient calculator as part of a project. The idea is to have a form where users can input values, and a corresponding doughnut chart will display with initial values set at 0. However, upon clicking the ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

Using *ngFor to Retrieve JSON Data Multiple Times

I'm trying to fetch 3 images from my endpoint that contains a large number of images using Angular's *ngFor directive (or any other suitable method) Below is my component.html <div class="col-sm-4 col-xs-6" *ngFor="let result o ...

Workspace watch mode does not update Typescript definitions

Greetings to all who are reading this, I have created a React micro-frontend project using SPA v5.9, Webpack v5.75, Babel-loader v9.1, Ts-loader v9.4, and Yarn workspace v3.5. The project structure is very basic: Root SPA => Package Root Application S ...

Tips for setting up a hierarchical mat-table within a parent table that supports expandable rows using Angular Material

Here is the data that I am working with: [ { "_id": "c9d5ab1a", "subdomain": "wing", "domain": "aircraft", "part_id": "c9d5ab1a", "info.mimetype": "application/json", "info.dependent": "parent", ...

What events can cause all store states to be loaded when the page is altered?

I am currently utilizing ngrx/store, ngrx/effects, and ngrx/router. The implementation of my effects is structured as follows: @Effect() loadOneProduct$ = this.updates$ .whenAction(LOAD_ONE_PRODUCT) .switchMap(() => this.productService.loadOn ...

Guide on implementing Regular Expressions in Directives for validation in Angular 8

Managing 8 different angular applications poses its unique challenges. In one of the applications, there is a directive specifically designed for validating YouTube and Vimeo URLs using regular expressions. Unfortunately, once the RegExp is declared, ther ...

Decide on the return type of a generic function depending on the parameters of the function

I have a series of TypeScript functions that are structured as follows: useCustomFunction = <T>(key: CustomType) : T => { // implementation details here } The parameter type is restricted to a specific set of strings: type CustomType = "apple ...

Please place the accurate image inside the designated box based on the corresponding ID number

I am currently working on a function that retrieves image data from a database and displays it in HTML using *ngFor directive. In order to display the correct image, I need to fetch the ID associated with the image data and use it to retrieve the correspo ...

What causes an error when the App is enclosed within a Provider component?

What is causing the error when wrapping the App in Provider? Are there any additional changes or additions needed? Error: "could not find react-redux context value; please ensure the component is wrapped in a @Provider@" import React from ' ...

Typescript Error:TS2345: The argument '{ theme: string; jsonFile: string; output: string; }; }' is not compatible with the parameter type 'Options'

Encountering an error mentioned in the title while using the code snippet below: import * as fs from 'fs' import { mkdirp } from 'mkdirp' import * as report from 'cucumber-html-reporter' const Cucumber = require('cucumber ...

The specified module could not be located in the ngx-toastr library

I'm having trouble finding the solution... ERROR in ./node_modules/ngx-toastr/fesm5/ngx-toastr.js Module not detected: Error: Unable to locate '/Users/vasanthan/Mean projects/node_modules/@angular/animations' in '/Users/vasanthan/Mean ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...

Incorporate an HTML code string into an Angular 2 template

I am working with HTML code stored in a Component variable, shown below: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `Hi <div [innerHTML]="name"></div>`, styleUrls: [' ...

How can I assign a true or false value to an input variable in HTML using AngularTS?

I copied the following HTML code: <tag-input fullWidth id="inputDir" formControlName="inputDir" [modelAsStrings]="true" [placeholder]="'choice feature'" ...

Testing Angular combineLatest with Jest

I'm encountering a challenge in an assessment involving a complex Statement related to combineLatest. Here is the snippet of code: component: export class ErinnerungenErinnerungenComponent implements OnInit, OnDestroy { ... erinnerungen: Erinne ...