हमारे पास लिटरल्स का ऐसा ऐरे है -
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
हमें एक जावास्क्रिप्ट फ़ंक्शन लिखना है जो इस ऐरे और एक नंबर 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 ]