 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to split last n digits of each value in the array with JavaScript?
We have an array of literals like this −
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
We are required to write a JavaScript function that takes in this array and a number n and if the corresponding element contains more than or equal to n characters, then the new element should contain only the last n characters otherwise the element should be left as it is.
Let's write the code for this function −
Example
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));  Output
The output in the console will be −
[ '', 19, 20, 21, 22, 23, 24, 25 ] [ '', 9, '0', 1, 2, 3, 4, 5 ] [ '', 1219, 1220, 1221, 1222, 1223, 1224, 1225 ]
Advertisements
 