Array.reduceRight() मेथड
reduceRight() ऐरे के एलिमेंट्स को दाएं से बाएं (राइट-टू-लेफ्ट) प्रोसेस करके सिंगल वैल्यू में रिड्यूस करता है। reduce() का उल्टा क्रम।
सिंटैक्स
array.reduceRight(callback(accumulator, currentValue, index, array), initialValue)
उदाहरण: नेस्टेड ऐरे को फ्लैट करना (राइट-टू-लेफ्ट)
<html> <body> <script> const arr = [ [1, 2, 3], ["x", "y", "z"], [9, 10] ]; // दाएं से बाएं कन्कैटनेट const flattened = arr.reduceRight((prev, curr) => prev.concat(curr)); document.write(flattened); </script> </body> </html>
आउटपुट
9,10,x,y,z,1,2,3
चरण-दर-चरण
| चरण | accumulator (prev) | currentValue (curr) | परिणाम |
|---|---|---|---|
| 1 | [9, 10] | ["x", "y", "z"] | [9, 10, "x", "y", "z"] |
| 2 | [9, 10, "x", "y", "z"] | [1, 2, 3] | [9, 10, "x", "y", "z", 1, 2, 3] |
reduce() vs reduceRight()
<script> var arr = [[1, 2], [3, 4], [5, 6]]; // reduce (बाएं से दाएं) arr.reduce((a, b) => a.concat(b)); // [1, 2, 3, 4, 5, 6] // reduceRight (दाएं से बाएं) arr.reduceRight((a, b) => a.concat(b)); // [5, 6, 3, 4, 1, 2] </script>
अन्य उपयोग: फंक्शन कम्पोजिशन (राइट-टू-लेफ्ट)
<script> const add1 = x => x + 1; const double = x => x * 2; const square = x => x * x; // f(g(h(x))) क्रम में लागू करने के लिए reduceRight const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x); const compute = compose(square, double, add1); // (x+1)*2 फिर स्क्वायर console.log(compute(3)); // ((3+1)*2)^2 = 64 </script>
महत्वपूर्ण नोट्स
- खाली ऐरे पर
initialValueके बिनाTypeErrorथ्रो करता है - मूल ऐरे नहीं बदलता
- कम उपयोग होता है
reduce()की तुलना में