ऑब्जेक्ट्स की ऐरे पर for लूप चलाएं और मॉड्यूलो ऑपरेटर (% 2 !== 0) से विषम (odd) CustomerId वाले रिकॉर्ड फिल्टर करें।
डेटा सेटअप
const customers = [
{ customerId: 101, customerName: "John" },
{ customerId: 102, customerName: "David" },
{ customerId: 103, customerName: "Mike" },
{ customerId: 104, customerName: "Bob" },
{ customerId: 105, customerName: "Alice" },
{ customerId: 106, customerName: "Charlie" }
];
विधि 1: बुनियादी for लूप
console.log("विषम CustomerId वाले ग्राहक:");
for (let i = 0; i < customers.length; i++) {
if (customers[i].customerId % 2 !== 0) {
console.log(`ID: ${customers[i].customerId}, नाम: ${customers[i].customerName}`);
console.log("---------------------------");
}
}
विधि 2: filter() मेथड (मॉडर्न, अनुशंसित)
const oddCustomers = customers.filter(c => c.customerId % 2 !== 0);
oddCustomers.forEach(c => {
console.log(`ID: ${c.customerId}, नाम: ${c.customerName}`);
});
विधि 3: for...of लूप (पठनीय)
for (const customer of customers) {
if (customer.customerId % 2 !== 0) {
console.log(`Customer Id: ${customer.customerId}`);
console.log(`Customer Name: ${customer.customerName}`);
console.log("---------------------------");
}
}
चलाने का तरीका
node odd-customers.js
आउटपुट
विषम CustomerId वाले ग्राहक:
ID: 101, नाम: John
---------------------------
ID: 103, नाम: Mike
---------------------------
ID: 105, नाम: Alice
---------------------------
विस्तार: सम/विषम दोनों के लिए जेनेरिक फंक्शन
function filterByIdParity(customers, wantOdd = true) {
return customers.filter(c =>
wantOdd ? c.customerId % 2 !== 0 : c.customerId % 2 === 0
);
}
console.log("विषम:", filterByIdParity(customers, true).map(c => c.customerName));
console.log("सम:", filterByIdParity(customers, false).map(c => c.customerName));
// विषम: [ 'John', 'Mike', 'Alice' ]
// सम: [ 'David', 'Bob', 'Charlie' ]
प्रदर्शन नोट
छोटी ऐरे के लिए कोई भी विधि ठीक है। बड़ी ऐरे के लिए filter() अधिक पठनीय और अनुकूलित है। for लूप सबसे तेज़ होता है लेकिन अधिक कोड लिखना पड़ता है।