Giả sử chúng ta có mảng chứa các số thẻ tín dụng demo như sau:
const arr = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];
Nhiệm vụ là tạo hàm nhận mảng này. Hàm phải trả về số thẻ tín dụng có tổng chữ số lớn nhất.
Nếu hai số thẻ có tổng bằng nhau, hàm trả về số thẻ cuối cùng.
Ví dụ
Mã thực hiện như sau:
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));
Kết quả
Kết quả trong console sẽ là:
4252-278893-7978