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
]

Updated on: 18-Sep-2020

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements