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
Splitting last n digits of each value in the array in JavaScript
We have an array of numbers and need to extract the last n digits from each value. If a number has fewer than n digits, it remains unchanged.
const arr = [56768, 5465, 5467, 3, 878, 878, 34435, 78799];
console.log("Original array:", arr);
Original array: [ 56768, 5465, 5467, 3, 878, 878, 34435, 78799 ]
We need a function that takes an array and a number n, then returns the last n digits of each element. If an element has fewer than n digits, it stays the same.
Example with n = 2
For n = 2, we want the last 2 digits of each number:
const arr = [56768, 5465, 5467, 3, 878, 878, 34435, 78799];
const splitLast = (arr, num) => {
return arr.map(el => {
if (String(el).length
Last 2 digits: [ 68, 65, 67, 3, 78, 78, 35, 99 ]
How It Works
The function converts each number to a string, checks its length, and extracts the last n characters using substr(). Finally, it converts back to a number.
// Step-by-step breakdown for 56768 with n=2
const number = 56768;
const str = String(number); // "56768"
const length = str.length; // 5
const lastTwoDigits = str.substr(length - 2, 2); // "68"
const result = +lastTwoDigits; // 68
console.log(`${number} ? ${result}`);
56768 ? 68
Alternative Using slice()
A cleaner approach using the modern slice() method:
const splitLastModern = (arr, num) => {
return arr.map(el => {
const str = String(el);
if (str.length
Using slice(): [ 768, 465, 467, 3, 878, 878, 435, 799 ]
Conclusion
Use String.slice(-n) to extract the last n digits from numbers. The function preserves numbers that are already shorter than n digits, making it reliable for mixed-length arrays.
