0

I have an array with one column n_fnc and I would like to find the max value . I tried with this but I don"t get anything.

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

[max aray

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);
2
  • to get a max of "simple elements": developer.mozilla.org/es/docs/Web/JavaScript/Referencia/… Commented Dec 24, 2020 at 9:12
  • This has nothing to do with the finding max. Just for the sake of performance, I recommend using regular for loop to find the max if possible. It seems like you just create another list from original and then reiterate to get the max. The list seems can be quite big imo. Looks like you can get the number relatively easy. Don't be obsessed with those fancy shortcut unless you want to reuse the max list somewhere else. Commented Dec 24, 2020 at 9:22

2 Answers 2

1

You can use apply function to do that -

var fncs = [{
 n_fnc: 1
},{
 n_fnc: 499
},{
 n_fnc: 99
},{
 n_fnc: 10
}];

var max = Math.max.apply(Math, fncs.map((m) => m.n_fnc));
console.log(max);

The code block in fnc.component.ts should be like -

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);
});
Sign up to request clarification or add additional context in comments.

6 Comments

I have fncs table as table of object . this.fncs=[]; this.fncservice.obs.subscribe((response)=>this.fncservice.getlastid(response,this.fncs)); var max= Math.max.apply(Math, this.fncs.map((m) => m.n_fnc)); I tried this but she return Infinity in max value
Can you post structure of your array?
@isawid, you are calling Math.max.apply outside of subscribe. It should be inside of subscribe block.
How I would do it ,please?
@isawid, I have updated my answer with fnc.component.ts snippet.
|
0

You can use apply function to do that -

let fncs = [{
 n_fnc: 1
},{
 n_fnc: 499
},{
 n_fnc: 99
},{
 n_fnc: 10
}];

let mytemp = fncs.sort((a, b) =>  { return b.n_fnc > a.n_fnc ? 1 : -1; });

console.log(mytemp[0]);

1 Comment

error in function(a,b) ... Type 'boolean' is not assignable to type 'number'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.