Adu Rao Adu Rao - 2 days ago 6
Javascript Question

Clip off last digits from arrays

I have the following array

var arr = ['1234','23C','456','356778', '56']


I want to remove array elements which are less than 3 characters and greater than 4 characters. The final result should be as follows

arr = ['1234', '23C', '456']; //only 3 and 4 digits in the array.


Secondly, I want to do the following. if 'arr' has elements longer than 3 characters, I need to clip of by removing the last digit. The final 'data' array should look like this.

arr = ['123', '23C', '456'];

Answer

For the first part, you can just use filter to filter out numbers that aren't composed of 3 digits.

var arr = [1234, 234, 456, 356778, 56];
var result = arr.filter(function(num) {
  return num < 1000 && num >= 100;
});

console.log(result);

For the second part, you can use map. Just convert the number to a string. If the length of it is greater than 3, take the substring composed of the first 3 elements of the string, then convert back to a number.

var data = [1234, 123, 4567, 3333];
var result = data.map(function(num) {
  num = num.toString().substring(0, 3);
  return parseInt(num);
});

console.log(result);

Comments