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
-
Economics & Finance
How to split last n digits of each value in the array with JavaScript?
We have an array of mixed values like numbers and strings, and we want to extract the last n digits from each element that has enough characters.
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
We need to write a JavaScript function that takes this array and a number n. If an element contains more than or equal to n characters, the function should return only the last n characters. Otherwise, the element should remain unchanged.
Solution
Here's how we can implement this function using the map() method and string manipulation:
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
]
How It Works
The function works by:
-
Converting to string:
String(el)converts each element to a string for uniform processing - Length check: If the string length is less than or equal to n, return the original element
-
Extracting substring:
substr()extracts the last n characters starting fromlength - numposition -
Type conversion:
+part || partconverts numeric strings back to numbers, but keeps non-numeric strings as strings
Alternative Using slice()
You can also use the modern slice() method instead of the deprecated substr():
const splitElementModern = (arr, num) => {
return arr.map(el => {
const str = String(el);
if (str.length <= num) {
return el;
}
const part = str.slice(-num);
return +part || part;
});
};
const testArr = ["", 20191219, 20191220, 20191221];
console.log(splitElementModern(testArr, 3));
[ '', 219, 220, 221 ]
Conclusion
This function efficiently extracts the last n digits from array elements using string manipulation and the map method. The slice(-num) approach is preferred over substr() for modern JavaScript development.
