merging arrays in d3.js

24 views
Skip to first unread message

Kuhu Gupta

unread,
May 26, 2016, 10:21:24 AM5/26/16
to datameet
My elex.csv is in this format-

"CONUM",PIXPMK","PIXMAR

"1","461","436" "2","398","428", "3","447","436" I want my dataset in this format-

var dataset1 = [ [1, 417], [1, 436], [2, 398], [2, 428], [3, 447], [3, 436]];

I have tried several times to get the fetch the data from csv in this form but all in vain.please help me out.I am attaching my code-

var dataset1 = [];

d3.csv("elex.csv", function(data) { dataset1 = data.map(function(d) { return [ [+d["CONUM"], +d["PIXMAR"]],[+d["CONUM"],+d["PIXPMK"]]]; }); console.log(dataset1) });

this returns me dataset1 as [[[1,417],[1,436]],[[2,398],[2,428]]]

Pratap Vardhan

unread,
May 26, 2016, 11:26:19 AM5/26/16
to datameet
You could use push() method with forEach()

var dataset = []
d3.csv('elex.csv', function(data) {
  data.forEach(function(d) {
    dataset.push(
      [+d["CONUM"], +d["PIXPMK"]],
      [+d["CONUM"], +d["PIXMAR"]]
      )
  })
})

JSON.stringify(dataset)
"[[1,461],[1,436],[2,398],[2,428],[3,447],[3,436]]"

However, you may want to use http://stackoverflow.com/ for code related question, has wider audience.

Regards,
Pratap

Curran Kelleher

unread,
May 27, 2016, 3:16:34 AM5/27/16
to datameet
Also cross-posted to D3 mailing list. Funny, we had the same solution!

Hi Kuhu,

Try this solution:

var dataset1 = [];
d3.csv("elex.csv", function(data) {
  data.forEach(function(d) {
    dataset1.push([+d.CONUM, +d.PIXMAR]);
    dataset1.push([+d.CONUM, +d.PIXPMK]);
  });
  console.log(dataset1);
});

map gives one entry per input row, but since you want two output entries per input row, you can use forEach to execute a function for each input row that creates the two output entries and adds them to dataset1.

All the best,
Curran
Reply all
Reply to author
Forward
0 new messages