Skip to content Skip to sidebar Skip to footer

How Do Your Write A Function That Returns Values From An Array?

I created this array: var lineData = [ { 'x': 25, 'y': 75}, { 'x': 85, 'y': 130}, { 'x': 140, 'y': 190}, { 'x': 195, 'y': 245}, { 'x': 195, 'y':

Solution 1:

Using a loop to access the data (as in the accepted answer) in a D3 code is a terrible idea: not only this is completely unnecessary, but it goes against the very concept of D3 data join, and it will make things awkward later on (if you try to manipulate/change that selection). If you will fix this with a loop, why are you using D3 in the first place? The solution you accepted is completely non-idiomatic.

You don't need a loop. Simply bind the data and use an "enter" selection, accessing the datum for each circle with the first parameter of the anonymous function: that's the famous function(d) in D3. When you do this...

.attr("cx", function(d){ return d.x})
//first parameter ---^

... the datum for each element will be passed to the attr function. In case you want to know, the second parameter is the index and the third parameter is the current group. Also, the actual name of the parameter doesn't matter, only its order.

Here is an example using your data:

var svg = d3.select("body")
  .append("svg")
  .attr("width", 600)
  .attr("height", 500);
  
var lineData = [ { "x": 25,   "y": 75},  { "x": 85,   "y": 130},
  { "x": 140,  "y": 190}, { "x": 195,  "y": 245},
  { "x": 195,  "y": 300}, { "x": 25,  "y": 350},
  { "x": 80,  "y": 405}, { "x": 195,  "y": 460}];
             
var ellipses = svg.selectAll("faraday")
  .data(lineData)
  .enter()
  .append("ellipse")
  .attr("cx", function(d){ return d.x})
  .attr("cy", function(d){ return d.y})
  .attr("rx", 5)
  .attr("ry", 5)
  .attr("fill", "teal");
<scriptsrc="https://d3js.org/d3.v4.min.js"></script>

Solution 2:

You can use the forEach method to go through every element in an array and get the values in each.

lineData.forEach(function(d) {
    // Draw an elipse
});

Put your code inside the brackets, use d.x and d.y to access coordinates in each element in the array.

Post a Comment for "How Do Your Write A Function That Returns Values From An Array?"