Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript - ผลรวมตัวเลขจากสตริงซ้อนในอาร์เรย์

สมมติว่าเรามีอาร์เรย์ที่มีหมายเลขบัตรเครดิตตัวอย่างแบบนี้:

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