

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Splitting last n digits of each value in the array in JavaScript
We have an array of literals like this −
const arr = [56768, 5465, 5467, 3, 878, 878, 34435, 78799];
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.
Therefore, if n = 2, for this array, the output should be −
const output = [68, 65, 67, 3, 78, 78, 35, 99];
Example
Following is the code −
const arr = [56768, 5465, 5467, 3, 878, 878, 34435, 78799]; const splitLast = (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(splitLast(arr, 2));
Output
This will produce the following output in console −
[ 68, 65, 67, 3, 78, 78, 35, 99 ]
- Related Questions & Answers
- How to split last n digits of each value in the array with JavaScript?
- Splitting number into n parts close to each other in JavaScript
- Splitting an array based on its first value - JavaScript
- Program to find last two digits of 2^n in C++
- Splitting an array into groups in JavaScript
- Splitting an array into chunks in JavaScript
- Absolute difference between the first X and last X Digits of N?
- Find last two digits of sum of N factorials using C++.
- Splitting an object into an array of objects in JavaScript
- Splitting Number into k length array in JavaScript
- Converting array to object by splitting the properties - JavaScript
- Top n max value from array of object JavaScript
- JavaScript Splitting string by given array element
- Returning an array containing last n even numbers from input array in JavaScript
- Find last k digits in product of an array numbers in C++
Advertisements