สมมติว่าเรามีอาร์เรย์ที่มีหมายเลขบัตรเครดิตตัวอย่างเช่นนี้ −
const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
เราได้รับมอบหมายให้สร้างฟังก์ชันที่ใช้ในอาร์เรย์นี้ ฟังก์ชันจะต้องส่งคืนหมายเลขบัตรเครดิตด้วยจำนวนหลักที่มากที่สุด
หากหมายเลขบัตรเครดิตสองหมายเลขมีผลรวมเท่ากัน หมายเลขบัตรเครดิตสุดท้ายจะถูกส่งคืนโดยฟังก์ชัน
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
const findGreatestNumber = (arr) => {
let n, i = 0, sums;
sums = [];
while (i < arr.length) {
sums.push(sum(arr[i]));
i++;
}
n = sums.lastIndexOf(Math.max.apply(null, sums));
return arr[n];
}
const sum = (num) => {
let i, integers, res;
integers = num.split(/[-]+/g);
i = 0;
res = 0;
while (i < integers.length) {
res += Number(integers[i]);
i++;
}
return res;
};
console.log(findGreatestNumber(arr)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
4252-278893-7978