map() के साथ टर्नरी ऑपरेटर (?) का उपयोग करके दो ऐरे में से प्रत्येक इंडेक्स पर उच्च मान वाले ऑब्जेक्ट को चुनें।
डेटा
const firstCustomers = [
{ firstName: 'John', amount: 100 },
{ firstName: 'David', amount: 50 },
{ firstName: 'Bob', amount: 80 }
];
const secondCustomers = [
{ firstName: 'John', amount: 400 },
{ firstName: 'David', amount: 70 },
{ firstName: 'Bob', amount: 40 }
];
map() + टर्नरी ऑपरेटर
const result = firstCustomers.map((obj, index) =>
obj.amount > secondCustomers[index].amount ? obj : secondCustomers[index]
);
console.log(result);
// [
// { firstName: 'John', amount: 400 }, // 400 > 100
// { firstName: 'David', amount: 70 }, // 70 > 50
// { firstName: 'Bob', amount: 80 } // 80 > 40
// ]
विस्तार: अलग-अलग लंबाई की ऐरे संभालें
function mergeByMaxProperty(arr1, arr2, prop) {
const maxLen = Math.max(arr1.length, arr2.length);
const result = [];
for (let i = 0; i < maxLen; i++) {
const a = arr1[i];
const b = arr2[i];
if (a && b) {
result.push(a[prop] > b[prop] ? a : b);
} else if (a) {
result.push(a);
} else if (b) {
result.push(b);
}
}
return result;
}
फ्लेक्सिबल: किसी भी प्रॉपर्टी द्वारा फिल्टर
function filterByProperty(array, property, condition) {
// condition: फंक्शन जो मान लेकर true/false लौटाता है
return array.filter(obj => condition(obj[property]));
}
// उपयोग: amount > 100 वाले
const highAmount = filterByProperty(firstCustomers, 'amount', v => v > 100);
console.log(highAmount); // [ { firstName: 'John', amount: 100 } ] - 100 > 100 false!
// amount >= 100
const highAmount2 = filterByProperty(firstCustomers, 'amount', v => v >= 100);
console.log(highAmount2); // [ { firstName: 'John', amount: 100 } ]
चलाने का तरीका
node filter-by-property.js
आउटपुट
[
{ firstName: 'John', amount: 400 },
{ firstName: 'David', amount: 70 },
{ firstName: 'Bob', amount: 80 }
]
महत्वपूर्ण मान्यताएं
- दोनों ऐरे समान लंबाई के हैं
- समान इंडेक्स पर तुलनीय ऑब्जेक्ट्स हैं
- तुलना के लिए प्रॉपर्टी दोनों में मौजूद है
बेहतर दृष्टिकोण: की द्वारा मर्ज (इंडेक्स नहीं)
function mergeByKey(arr1, arr2, key, valueProp) {
const map = new Map();
[...arr1, ...arr2].forEach(item => {
const k = item[key];
if (!map.has(k) || item[valueProp] > map.get(k)[valueProp]) {
map.set(k, item);
}
});
return Array.from(map.values());
}
console.log(mergeByKey(firstCustomers, secondCustomers, 'firstName', 'amount'));
// इंडेक्स क्रम पर निर्भर नहीं