समस्या
हमें एक JavaScript फ़ंक्शन लिखना है जो नंबर्स (पॉजिटिव और नेगेटिव) का एक ऐरे लेता है। हमारा फ़ंक्शन ऐरे में मौजूद सभी पॉजिटिव नंबर्स का योग गणना करके लौटाएगा।
उदाहरण
निम्नलिखित कोड है −
const arr = [5, -5, -3, -5, -7, -8, 1, 9]; const sumPositives = (arr = []) => { const isPositive = num => typeof num === 'number' && num > 0; const res = arr.reduce((acc, val) => { if(isPositive(val)){ acc += val; }; return acc; }, 0); return res; }; console.log(sumPositives(arr));आउटपुट
कंसोल आउटपुट निम्नलिखित है −
15