-1

I have array:

var data = [];
data.genre = [ 'AAAA', '2', 'CCCc', '3', 'dDdDD' ];

a need to remove all string from array and return only numbers...so above return i need to be:

data.genre = [ '2', '3' ];

I try with this:

alert(data.genre.map(function(x){ return x.replace(/^\d+\.\s*/,"") }));

But nothing is changed...so i need to make whole array remove strings and leave only numbers...this i need to get id with this numbers in my mysql left join genre on id.

John
  • 1,521
  • 3
  • 15
  • 31

3 Answers3

5

Use Array#filter():

var data = {};
data.genre = [ 'AAAA', '2', 'CCCc', '3', 'dDdDD', '', ' ' ];

data.genre = data.genre.filter(function (str) {
  return str.trim() && !isNaN(str);
});

console.log(data.genre);

This method uses the global function isNaN() to determine if the string can be coerced to a numerical value. If not, isNaN() returns true so we must negate ! that, in order to filter numeric strings. In addition, it preflights this check with String#trim(), and empty strings evaluated as a Boolean are falsy, so strings with whitespace only shall not pass.

Another comment, make sure that you declare data as an object {} instead of an array [] if you're going to assign it arbitrary properties. Arrays are used for storing ordered data.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
4

You could filter with a regular expression which test for digits only.

var data = {};
data.genre = [ 'AAAA', '2', 'CCCc', '3', 'dDdDD' ];

data.genre = data.genre.filter(function (a) {
    return /^\d+$/.test(a);
});

console.log(data);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use Array.prototype.filter for this. Array.filter takes in a callback function which should return true or false and will composite a new array based on the true/false outputs.

Jrs.b
  • 61
  • 6