I am new from D3 (using v3) I have a data structure like below:
var data=[
{"name":"airport","values":[
{"x":zero ,"y":333},
{"x":one,"y":138},
{"x":two,"y":118}
]},
{"name":"train","values":[
{"x":zero,"y":136},
{"x":one,"y":217},
{"x":two,"y":109}
]},
{"name":"car","values":[
{"x":zero,"y":132},
{"x":one,"y":244},
{"x":two,"y":145}
]}
]
I would like to use data.map to re-map an array like the follow format
["zero", "one", "two"]
what is the correct way to get only x value to form an array in d3?
Many thanks
I have made changes in "x" values as following i have just added "" to every element. As it is not number it will be treated as string
{"x":"zero","y":333},
{"x":"one","y":138},
{"x":"two","y":118}
In your case, you can just add
d3.scale.ordinal().domain(data[0].values.map(function(element){
return element.x
}))
It will give you array as you were expecting ["zero", "one", "two"].
Above solution is for when you have fix x labels but if you wish to traverse through each element to see or add more you can use this approach or for generic solution
d3.scale.ordinal().domain(filter(data))
function filter(localData){
var tempdata = []
localData.forEach(function (element){
return element.values.forEach(function(element){
tempdata.push(element.x)
})
})
var uniqueArray = tempdata.filter(function(item, pos, self) {
return self.indexOf(item) == pos;
})
return uniqueArray
}