2016-09-26 1 views
1

을 반환하는 것은 다음과배열 내가 유사한 코드가 NAN

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}]; 

var reduced=temp.reduce(function (a,b) { 
     return a.y + b.y; 
    }); 
console.log(reduced) // returns NAN 
+1

을 감소 - 당신의 대해서 typeof'A' 의지 최초의 합계를 반환하면 숫자 여야합니다 - 어떤 y 속성도 없습니다 –

+0

check reduce 함수의 콜백 매개 변수는 무엇입니까? – passion

답변

14

당신은 시작 값과 추가 배열에서 하나 개의 값을 사용할 수 있습니다.

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}]; 
 

 
var reduced = temp.reduce(function (r, a) { 
 
     return r + a.y; 
 
     // ^^^ use the last result without property 
 
    }, 0); 
 
// ^^^ add a start value 
 
console.log(reduced) // r

+0

하나의 라이너 const가 감소됨 = temp.length? temp.reduce ((r, a) => {return r + a.y;}, 0) : 0; – webmaster

+0

@webmaster, 더 짧아도 빈 배열의 경우 reduce의 시작 값을 취합니다 :'const reduced = temp.reduce ((r, {a}) => r + a, 0); –

2

짧은 솔루션 :이 문제를 설명하기 위해 정수 컬렉션 컬렉션을지도하고, 그것을

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}]; 

var reduced = temp 
       .map(function(obj) { return obj.y; }) 
       .reduce(function(a, b) { return a + b; }); 

console.log(reduced); 
관련 문제