Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

289
Views
Unable to pass javascript literal from array values to D3 function

I'm trying to pass some array values into a d3 scaleLinear function. The current function looks like this:

const y = d3.scaleLinear()
        .domain([0, d3.max(data, d =>
          d.public +
          d.private
        )])
        .range([height, 0]);

What I would like to do is pass d.public and d.private from an array that defines these:

const keys = [
      "private",
      "public"
    ]

So that I can use them (and pass different keys depending on the data) in the function as:

const y = d3.scaleLinear()
        .domain([0, d3.max(data, d =>
          `d.${keys[0]}` +
          `d.${keys[1]}`
        )])
        .range([height, 0]);

I've tried several different variations on the syntax above without success. TIA.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are passing string literal to domain rather than values. d.${keys[0]} translates to 'd.private' and not object.private Use a function or pass d[keys[0]]..Doing an example for you below with a function ( which gives better flexibility in case you have complex data)

let data = [{
  "private": 10,
  "public": 20
}, {
  "private": 40,
  "public": 30
}, {
  "private": 20,
  "public": 60
}]

const keys = ["private", "public"];
let valueOf = (d, key) => d[key];

const x = d3.scaleLinear()
  .domain([0, d3.max(data, d =>
    valueOf(d, keys[0]) +
    valueOf(d, keys[1])
  )])
  .range([0, 300]);

let points = [0, 12, 45, 34, 77.72, 59.11, 9.99];


d3.select('svg .scal')
  .selectAll('circle')
  .data(points)
  .enter()
  .append('circle')
  .attr('r', 3)
  .attr('fill', "green")
  .attr('cx', function(d) {
    return x(d);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<body>
  <svg width="400" height="40">
<g class="scal" transform="translate(40, 30)"></g></svg>
</body>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!