Hi guys can you explain me the differences between this two kind of implementations?
var vettoreC: Array<number> = [];
vettoreC = vettoreA;
this.moda = (function mode(vettoreC) {
return vettoreC.sort((a, b) =>
vettoreC.filter(v => v === a).length - vettoreC.filter(v => v === b).length
).pop();
})();
and
var vettoreC: Array<number> = [];
vettoreC = vettoreA;
this.moda = this.calcolaModa (vettoreC);
where calcolaModa is
calcolaModa(vettore: Array<number>) {
return vettore.sort((a, b) =>
vettore.filter(v => v === a).length - vettore.filter(v => v === b).length
).pop();
}
In the first case I have this error:
ERROR TypeError: Cannot read property 'sort' of undefined
at mode (statistiche.component.ts:145)
at statisticheComponent.webpackJsonp.128.statisticheComponent.calcolaStatistiche (statistiche.component.ts:148)
at SafeSubscriber._next (statistiche.component.ts:72)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.next (Subscriber.js:185)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at CatchSubscriber.Subscriber._next (Subscriber.js:125)
The second works correctly.
What could i do to make valid the first implementation?
1 Answer 1
With the first example, you'll need to pass the arguments in the last parentheses:
this.moda = (function mode(vettoreC) {
return vettoreC.sort((a, b) =>
vettoreC.filter(v => v === a).length - vettoreC.filter(v => v === b).length
).pop();
})(vettoreC);
Notice the last line where the vettoreC is mentioned again.
answered May 31, 2017 at 9:04
Douwe de Haan
6,7253 gold badges35 silver badges53 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Douwe de Haan
@MarcoNatale No problem, happy to help!
lang-js