I am trying to convert the below function into arrow function using ES6,
$scope.sum = function(list, prop){
return list.reduce( function(a, b){
return a + b[prop];
}, 0);
};
I tried below,
$scope.sum = (list,prop) => {return list.reduce((a,b) => {return (a+ b[prop])}, 0)};
throwing this error Cannot read property 'reduce' of undefined
i am using in angular 1.5
I am trying to convert the below function into arrow function using ES6,
$scope.sum = function(list, prop){
return list.reduce( function(a, b){
return a + b[prop];
}, 0);
};
I tried below,
$scope.sum = (list,prop) => {return list.reduce((a,b) => {return (a+ b[prop])}, 0)};
throwing this error Cannot read property 'reduce' of undefined
i am using in angular 1.5
Share Improve this question edited Nov 8, 2018 at 22:51 mahesh babu asked Nov 8, 2018 at 22:32 mahesh babumahesh babu 311 silver badge7 bronze badges 6-
2
That error would have to be happening because you're calling
$scope.sum()
somewhere with an undefined variable for the list. – Herohtar Commented Nov 8, 2018 at 22:36 - 2 What Herohtar is saying is that the error is independent of the arrow functions, it happens with the old function too. – Tamas Hegedus Commented Nov 8, 2018 at 22:38
- Old function with $scope.sum is working good, now I am trying to ment the old function and trying to do it in Es6...I think what ever i written in es6 syntax there is wrong i hope – mahesh babu Commented Nov 8, 2018 at 22:46
- 3 The syntax of both of those functions is fine. The problem is somewhere else in your code. – Herohtar Commented Nov 8, 2018 at 22:56
-
2
then you must have changed something else, because the two implementations are eqivalent. Plus a more concise version of your code
$scope.sum = (list, prop) => list.reduce((a,b) => a+b[prop], 0);
– Thomas Commented Nov 8, 2018 at 22:58
1 Answer
Reset to default 4Your two functions are identical.
const sum1 = function(list, prop){ return list.reduce( function(a, b){ return a + b[prop];}, 0);};
const sum2 = (list,prop) => { return list.reduce((a,b) => {return (a+ b[prop])}, 0)};
const list = [{foo:1},{foo:2},{foo:3}]
console.log(sum1(list, 'foo'));
console.log(sum2(list, 'foo'));