3

How can we extract integer (keys) from such a data set ?

data : {
    DAYS7: 234,
    DAYS21: 3456,
    DAYS35: 23456
}

I want to convert this data into two arrays [7, 21, 35] and [234, 3456, 23456].

Code:

var a = [], b = [];
for (var key in data) {
  a.push(getIntPart(key));
  b.push(data[key]);
}

function getIntPart(key) {
  key = key.substring(4); //Remove DAYS word
  return parseInt(key);
} 

I think key.substring(4) is not the right way to do it because it will fail for some other key. Please suggest how should I solve this issue.

2
  • You're missing a ) on that first push btw. Commented Mar 4, 2014 at 15:17
  • @Andy Thanks for telling me the typo Commented Mar 4, 2014 at 15:27

3 Answers 3

6

You may use regular expression:

key = (key.match(/\d+$/) || []).pop();

This will match all numbers (\d+) at the end ($) of key string.

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

1 Comment

Oh right..Why didn't I think of this..Thanks a lot..I think it will do.
1

If it's only every "DAYS" you need to remove use a simple replace:

a.push(+k.replace('DAYS', ''));

Fiddle

Or, using your example:

function getIntPart(key) {
  key = key.replace('DAYS', '');
  return parseInt(key);
}

Comments

0

Alternatively you can use split here and extract the second token:

key = key.split(/(\d+)/)[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.