JavaScript-এ ফর লুপ এবং মডুলো অপারেটর (%) ব্যবহার করে অবজেক্ট অ্যারে থেকে বিজোড় (odd) কাস্টমার আইডি वाले রেকর্ড ফিল্টার করা যায়।
ডেটা
const customers = [
{ customerId: 101, customerName: "John" },
{ customerId: 102, customerName: "David" },
{ customerId: 103, customerName: "Mike" },
{ customerId: 104, customerName: "Bob" }
];
ফর লুপ পদ্ধতি
for (let i = 0; i < customers.length; i++) {
if (customers[i].customerId % 2 !== 0) { // বিজোড় চেক
console.log("Customer ID: " + customers[i].customerId);
console.log("Customer Name: " + customers[i].customerName);
console.log("---------------------------");
}
}
চলানোর পদ্ধতি
- কোডটি
oddFilter.jsনামে সংরক্ষণ করুন। - টার্মিনালে চালান:
node oddFilter.js
আউটপুট
Customer ID: 101
Customer Name: John
---------------------------
Customer ID: 103
Customer Name: Mike
---------------------------
আধুনিক ফাংশনাল পদ্ধতি
// filter + forEach
customers
.filter(c => c.customerId % 2 !== 0)
.forEach(c => {
console.log(`ID: ${c.customerId}, Name: ${c.customerName}`);
});
// শুধু নামের অ্যারে
const oddNames = customers
.filter(c => c.customerId % 2 !== 0)
.map(c => c.customerName);
console.log(oddNames); // ['John', 'Mike']
মডুলো অপারেটর রেফারেন্স
| এক্সপ্রেশন | ফলাফল | অর্থ |
|---|---|---|
n % 2 === 0 | true | জোড় (Even) |
n % 2 !== 0 | true | বিজোড় (Odd) |
n % 2 === 1 | true | বিজোড় (পজিটিভ নম্বর) |
আরো জটিল ফিল্টার
// বিজোড় ID এবং নাম 'J' দিয়ে শুরু
const complexFilter = customers.filter(c =>
c.customerId % 2 !== 0 && c.customerName.startsWith('J')
);
// [{ customerId: 101, customerName: 'John' }]