Reputation: 11
Struggling with this, and have red all the similar questions.
I am using d3 library to read in a csv on a webpage.
I currently have this:
d3.csv("normal.csv", function(rows) {
doSomethingWithRows(rows);
});
function doSomethingWithRows(rows) {
// do something with rows
console.log(rows);
}
This outputs me this:
-an array for all the rows
-each index as object (each row is an object)
so its an array with objects.
What I would like is an array of arrays, so i could reference things like an 2D array.
I looked at jquery-csv but that didnt help in converting to array of array. Also looked at d3.csv.parser but it didnt help either.
Any ideas
Upvotes: 1
Views: 3239
Reputation: 6366
There are a few ways to understand what you are trying to do.
Each object should correspond to an array within the outer array, which does not change length. In which case, you want map or an accessor function (see docs for d3.csv).
You want to keep the same number of elements but arrange them with two indices instead of one. In this case, I recommend you keep your data as one-dimensional and do math on the index later. D3 makes the array index available to you whenever you'd need it.
You want to create a 2D array where each element draws from multiple objects in the array you have. The exact transformation depends on what you're trying to do, but I would look at the D3 docs for Arrays, which helpfully list some plain JavaScript methods at the top. In particular, look at pairs
and zip
. You can also look at the nest
data structure. If you want a grid or matrix, see this example and in particular the function cross
.
(In response to comment) You want to use the 2D structure of the CSV itself. You basically already have this, except that the inner data structure is key-value rather than by index. This takes advantage of CSV headers and the fact that CSV columns is frequently heterogenous and do not admit numerical ordering. If you really want to change the values into an array, use map or an accessor function. By I can't really see why you'd want to, besides d3.transpose.
That being said, D3 code (or at least the simplest D3 code) is oriented around one-dimensional data. You should think hard about whether you really need a 2D array. It's hard to jump right in to D3 and make your own charts; you'd do well to read some tutorials and get a sense for how it works and the opinions it has.
Upvotes: 2