Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 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
