ฟังก์ชันนี้รับอาร์เรย์และตัวเลข n แล้วคืนอาร์เรย์ใหม่ที่แต่ละสมาชิกเป็น n หลักสุดท้ายของสมาชิกเดิม (ถ้ามีหลักน้อยกว่า n ให้คงเดิม)
ตัวอย่าง
Input: [56768, 5465, 5467, 3, 878, 878, 34435, 78799], n = 2 Output: [68, 65, 67, 3, 78, 78, 35, 99]
ตัวอย่างโค้ด
const arr = [56768, 5465, 5467, 3, 878, 878, 34435, 78799];
const splitLast = (arr, num) => {
return arr.map(el => {
const str = String(el);
if (str.length <= num) return el;
const part = str.substr(str.length - num, num);
return +part || part; // แปลงเป็นตัวเลข ถ้าไม่ได้ให้คืนสตริง
});
};
console.log(splitLast(arr, 2));
ผลลัพธ์
[ 68, 65, 67, 3, 78, 78, 35, 99 ]