
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Split 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 ]
Advertisements