เรามีอาร์เรย์ของค่าตรงตัวแบบนี้
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์นี้และตัวเลข n และถ้าองค์ประกอบที่สอดคล้องมีตัวอักษรมากกว่าหรือเท่ากับ n องค์ประกอบใหม่ควรมีเฉพาะ n ตัวอักษรสุดท้าย มิฉะนั้นองค์ประกอบควรคงเดิม
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน
ตัวอย่าง
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
const splitElement = (arr, num) => {
return arr.map(el => {
if(String(el).length <= num){
return el;
};
const part = String(el).substr(String(el).length - num, num);
return +part || part;
});
};
console.log(splitElement(arr, 2));
console.log(splitElement(arr, 1));
console.log(splitElement(arr, 4));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
[ '', 19, 20, 21, 22, 23, 24, 25 ] [ '', 9, '0', 1, 2, 3, 4, 5 ] [ '', 1219, 1220, 1221, 1222, 1223, 1224, 1225 ]