reduce() का उपयोग करके दोनों ऐरे को एक साथ प्रोसेस करें, प्रत्येक नाम के लिए उच्चतम मान वाला ऑब्जेक्ट रखें - कन्कैटनेशन की आवश्यकता नहीं।
डेटा
const sectionA = [
{ studentName: 'John', studentMarks: 78 },
{ studentName: 'David', studentMarks: 65 },
{ studentName: 'Bob', studentMarks: 98 }
];
const sectionB = [
{ studentName: 'John', studentMarks: 67 },
{ studentName: 'David', studentMarks: 89 },
{ studentName: 'Bob', studentMarks: 97 }
];
reduce() समाधान (कन्कैट के बिना)
function mergeByMax(arr1, arr2, key, valueKey) {
// पहले ऐरे से मैप बनाएं
const map = new Map();
arr1.forEach(item => map.set(item[key], item));
// दूसरे ऐरे से मर्ज करें - उच्च मान रखें
arr2.forEach(item => {
const existing = map.get(item[key]);
if (!existing || item[valueKey] > existing[valueKey]) {
map.set(item[key], item);
}
});
return Array.from(map.values());
}
const result = mergeByMax(sectionA, sectionB, 'studentName', 'studentMarks');
console.log(result);
reduce() के साथ संक्षिप्त संस्करण
const mergeMax = (acc, item) => {
const existing = acc.find(x => x.studentName === item.studentName);
if (!existing || item.studentMarks > existing.studentMarks) {
// मौजूदा को हटाएं और नया जोड़ें
const idx = acc.indexOf(existing);
if (idx !== -1) acc.splice(idx, 1);
acc.push(item);
}
return acc;
};
const combined = [...sectionA, ...sectionB].reduce(mergeMax, []);
console.log(combined);
सिंगल reduce पास (दोनों ऐरे पर)
function combineSections(sectionA, sectionB) {
const reducer = (acc, curr) => {
const existing = acc[curr.studentName];
if (!existing || curr.studentMarks > existing.studentMarks) {
acc[curr.studentName] = curr;
}
return acc;
};
// दोनों ऐरे पर reduce चलाएं, एक ही एक्यूमुलेटर के साथ
const merged = sectionA.reduce(reducer, {});
sectionB.reduce(reducer, merged);
return Object.values(merged);
}
console.log(combineSections(sectionA, sectionB));
आउटपुट
[
{ studentName: 'John', studentMarks: 78 }, // A से (78 > 67)
{ studentName: 'David', studentMarks: 89 }, // B से (89 > 65)
{ studentName: 'Bob', studentMarks: 98 } // A से (98 > 97)
]
चलाने का तरीका
node merge-max.js
क्यों कन्कैट नहीं?
- मेमोरी: बड़ी ऐरे के लिए मध्यवर्ती ऐरे नहीं बनती
- प्रदर्शन: सिंगल पास, O(n) बनाम O(n) कन्कैट + O(n) प्रोसेस
- स्ट्रीमिंग: डेटा चंक्स में आ सकता है, सभी एक साथ नहीं
जेनेरिक फंक्शन
function mergeArraysByKeyMax(...arrays) {
const map = new Map();
for (const arr of arrays) {
for (const item of arr) {
const key = item.studentName; // या पैरामीटर से
const existing = map.get(key);
if (!existing || item.studentMarks > existing.studentMarks) {
map.set(key, item);
}
}
}
return Array.from(map.values());
}
// किसी भी संख्या में ऐरे
console.log(mergeArraysByKeyMax(sectionA, sectionB, sectionC, sectionD));