----------------------------------------------------------
Extracting data from a portion of a string.
The example problem here would be as if we have a set of values in a string that we want to extract but which in their original form it would not be possible.
For example, the following csv file contains the column ‘value’ and the values of the data in that column are prefixed with a dollar sign ($).
value,date,score
$1234,2011-03-23,99
$2234,2011-03-24,100
$3234,2011-03-25,99
$4235,2011-03-26,100
We can use the JavaScript substring() method to easily remove the leading character from the data.
The following example processes our csv file after loading it and for each ‘value’ entry on each row takes a substring of the entry that removes the first character and retains the rest.
d3
.
csv
(
"sample-data.csv"
,
function
(
error
,
data
)
{
data
.
forEach
(
function
(
d
)
{
d
.
value
=
+
d
.
value
.
substring
(
1
);
});
...
});
The substring() function includes a ‘start’ index (as used above) and optionally a ‘stop’ index. More on how these can be configured can be found on the w3schools site.
value,date,score
$1234,2011-03-23,99
$2234,2011-03-24,100
$3234,2011-03-25,99
$4235,2011-03-26,100
d3
.
csv
(
"sample-data.csv"
,
function
(
error
,
data
)
{
data
.
forEach
(
function
(
d
)
{
d
.
value
=
+
d
.
value
.
substring
(
1
);
});
...
});
The description above (and heaps of other stuff) is in the D3 Tips and Tricks book that can be downloaded for free (or donate if you really want to :-)).
does it actually work,pls post an working example.
ReplyDeleteYep. It really works :-). The example code in the description will work for d3.js and the recommended link in the text to w3schools has a good alternative https://www.w3schools.com/jsref/jsref_substring.asp
Delete