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.
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>