mahesh babu
mahesh babu

Reputation: 31

Convert normal function to arrow function

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

Upvotes: 2

Views: 7676

Answers (1)

H.P.
H.P.

Reputation: 86

Your 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'));

Upvotes: 4

Related Questions