skip to Main Content

I have an array that consists of multiple elements so what I want to do is remove the last two digits from the array element if the array element consists of 3 or 4 digits then remove the last two digits from it. and if the element is 1 or 2 digits then it will remain the same.

var test =[ 2, 45,567, 3, 6754];

Then the output that I need is :

[ 2, 45, 5, 3, 67];

I have tried this

test.forEach(function(element, index) {    test[index] = element.slice(1, -2); }); 

But this will remove the single digits element to blank

2

Answers


  1. Solution you wrote would not work at all, because u try to slice values with type number.

    Try this:

    test.forEach(function(element, index) {    test[index] = String(element).length > 2 ? +String(element).slice(0, -2) : test[index]}); 
    
    Login or Signup to reply.
  2. You could divide the value by 100 and take the integer value, if necessary.

    const
        data = [2, 45, 567, 3, 6754],
        result = data.map(v => v >= 100 ? Math.floor(v / 100) : v);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search