How to split last n digits of each value in the array with JavaScript?


We have an array of literals like this −

const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];

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.

Let's write the code for this function −

Example

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));

Output

The output in the console will be −

[
   '', 19, 20, 21,
   22, 23, 24, 25
]
[
   '', 9, '0', 1,
   2, 3, 4, 5
]
[
   '', 1219, 1220,
   1221, 1222, 1223,
   1224, 1225
]

Updated on: 31-Aug-2020

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements