다음과 같은 데모 신용 카드 번호가 포함된 배열이 있다고 가정해 보겠습니다.
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