for लूप से ऐरे के प्रत्येक एलिमेंट को एक्यूमुलेटर वेरिएबल में जोड़कर कुल योग निकालें।
बुनियादी for लूप
const numbers = [10, 3, 4, 90, 34, 56, 23, 100, 200];
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total = total + numbers[i];
// या संक्षिप्त: total += numbers[i];
}
console.log("कुल योग:", total); // 520
अन्य लूप विधियां
// for...of (ES6 - पठनीय)
let total = 0;
for (const num of numbers) {
total += num;
}
// forEach
let total = 0;
numbers.forEach(num => total += num);
// reduce (फंक्शनल, सबसे आम)
const total = numbers.reduce((sum, num) => sum + num, 0);
console.log(total); // 520
reduce() विस्तार से
const numbers = [10, 3, 4, 90, 34, 56, 23, 100, 200];
// reduce(कॉलबैक, प्रारंभिक_मान)
const sum = numbers.reduce((accumulator, currentValue) => {
console.log(`acc: ${accumulator}, curr: ${currentValue} → ${accumulator + currentValue}`);
return accumulator + currentValue;
}, 0);
/* कंसोल आउटपुट:
acc: 0, curr: 10 → 10
acc: 10, curr: 3 → 13
acc: 13, curr: 4 → 17
...
acc: 320, curr: 200 → 520
*/
चलाने का तरीका
node sum-array.js
आउटपुट
कुल योग = 520
प्रदर्शन तुलना
| विधि | पठनीयता | प्रदर्शन | फंक्शनल |
|---|---|---|---|
| for लूप | मध्यम | सबसे तेज़ | नहीं |
| for...of | उच्च | तेज़ | नहीं |
| forEach | उच्च | मध्यम | नहीं |
| reduce | उच्च | मध्यम | ✅ हां |
एडवांस्ड: ऑब्जेक्ट्स की ऐरे में विशिष्ट प्रॉपर्टी का योग
const students = [
{ name: "John", marks: 78 },
{ name: "Jane", marks: 85 },
{ name: "Bob", marks: 92 }
];
const totalMarks = students.reduce((sum, student) => sum + student.marks, 0);
console.log("कुल अंक:", totalMarks); // 255
// औसत
const average = totalMarks / students.length;
console.log("औसत:", average); // 85