You may use regular expression:
key = (key.match(/\d+$/) || []).pop();
This will match all numbers (\d+
) at the end ($
) of key
string.
Question
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.
Solution
You may use regular expression:
key = (key.match(/\d+$/) || []).pop();
This will match all numbers (\d+
) at the end ($
) of key
string.
OTHER TIPS
If it's only every "DAYS" you need to remove use a simple replace
:
a.push(+k.replace('DAYS', ''));
Or, using your example:
function getIntPart(key) {
key = key.replace('DAYS', '');
return parseInt(key);
}
Alternatively you can use split here and extract the second token:
key = key.split(/(\d+)/)[1]