JoshuaNa
JoshuaNa

Reputation: 23

jquery trim last 2 zeros from an array

I have an array

var aa = ["500", "600", "700", "800", "900", "1000", "1100", "1200"]

I need to strip last 2 zeros. I have the script like this below but that strips the array values

$( '.hasDifficutly span' ).each(function(  ) {
var a = $(this).text();
  var aa = a.split(', ');  

  if (aa.length > 2) {
    aa = [aa.shift(), aa.pop()]
  }  

  $(this).text(aa.slice(0,-2));

});

so instead of getting ["500", "1200"] I get [] but I need ["5", "12"]

Upvotes: 0

Views: 53

Answers (2)

Davuz
Davuz

Reputation: 5276

You can try Array.map() and divise 100:

aa.map(function(item){
    return !isNaN(item) && item%100 == 0 ? Math.floor(item/100) : item;
})

In your case, modify the code to:

$( '.hasDifficutly span' ).each(function(  ) {
    var a = $(this).text();
    var aa = a.split(', ');  
    aa = aa.map(function(item){
         return !isNaN(item) && item%100 == 0 ? Math.floor(item/100) : item;
    });
    $(this).text(aa.join(','));
 });

Upvotes: 1

ameenulla0007
ameenulla0007

Reputation: 2683

var aa = ["500", "600", "700", "800", "900", "1000", "1100", "1200", '1'];
var newArray = [];
$.each(aa, function( index, value ) {
    var valPush = parseInt(value)<=99 ? value : value.slice(0,-2);
    newArray.push(valPush);
});
alert(newArray.join(","));

here it is, you can use the above code to make it working your way..

working Fiddle : https://jsfiddle.net/d9807kbo/

Upvotes: 1

Related Questions