-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.

5
  • 2
    You should be using filter not map. Commented Jun 30, 2017 at 19:29
  • 1
    So data should be an object not array? Commented Jun 30, 2017 at 19:29
  • Can this be used as regex or somthing familiar? that removes string Commented Jun 30, 2017 at 19:30
  • Do you want to keep "1.2"? Commented Jun 30, 2017 at 19:53
  • Above answer is correct..simple and easy..thanks Commented Jun 30, 2017 at 20:00

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

12 Comments

the former version was better, why did you make it more complex ?
Instead of that insanity, why not .filter(//.test, /^\d+$/)?
ok, you get the old version back.
@torazaburo now I wish I could undo my upvote on your comment. That's a comment, not a regular expression, and RegExp.prototype.test is better anyway because it does not create an unused variable.
@torazaburo actually //.test makes a comment.
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.