Reputation: 89
I've successfully mapped the returned data to an array (selected.data().map(d=>d)
) and can console log its contents to the console. However, the data includes both integers and strings. With this, I'd like to be able to log only the strings to the console. My approach below creates a new variable and filters through theSelection
and returns data that is a typeof
string. But nothing is being printed to the console (and no errors are being returned). If someone out there is able to look over my code and tell me where I'm going wrong, that would be helpful.
selected = lasso.selectedItems()
.classed("selected", true)
.attr("r", 18);
console.log(selected);
var theSelection = selected.data().map(d=>d);
console.log(theSelection);
var result = theSelection.filter(d => typeof d === 'String');
console.log(result);
for(var i = 0; i < result.length; i++) {
console.log(result[i]);
}
Data
var data = [
["Acid", 0.741593940836, 0.45657115, "Bristol", "Cardiff", "Birmingham"],
["Cannabis", 0.94183423, 0.31475, "Chester", "Swansea", "Brighton"],
["LSD", 0.1367547, 0.936115, "Newcastle", "Cardiff", "Bristol"],
];
Upvotes: 1
Views: 1393
Reputation: 2768
First off, your map line:
var theSelection = selected.data().map(d=>d);
..does nothing. It is basically saying, "map every element in the array to itself and return that array" (which is the same as the original array because no transformation has happened).
Because of this, your array theSelected
is actually still a matrix (an array of arrays). Therefore, your filter statement is iterating through an array of only one item (another array with six items in it), and failing the typeof
check because it is an array not a String
.
You would need to utilize some other transform to flatten your "matrix" into one array like so:
const theSelection = [];
selected.data().forEach((arr) => {
arr.forEach((d) => { theSelection.push(d); });
});
Upvotes: 1
Reputation: 30739
You need to do typeof d === 'string'
as d === typeof "string"
is incorrect because d
refers to the value and you should check the type of d
to be of string
type.
var theSelection = ['Acid', 'str', 0.123545, 'Bristol'];
var result = theSelection.filter(d => typeof d === 'string');
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
Upvotes: 1