I'd like to populate a dropdown list (select tag) with only unique values from an object.
This is the object with the data:
[
{
"code": 1,
"abbr": "BR",
"vote": 49277010
},
{
"code": 1,
"abbr": "BR",
"vote": 31342051
},
{
"code": 43,
"abbr": "RS",
"vote": 3353623
},
{
"code": 31,
"abbr": "MG",
"vote": 3037957
},
{
"code": 31,
"abbr": "MG",
"vote": 5017922
},
{
"code": 35,
"abbr": "SP",
"vote": 2650440
},
{
"code": 42,
"abbr": "SC",
"vote": 2603665
},
{
"code": 1,
"abbr": "BR",
"vote": 71347057
},
{
"code": 26,
"abbr": "PE",
"vote": 2309104
}
]
And here is how I get the data to build the dropdown list:
//initialize the dropdown
var dropdown = d3.select("#sel")
dropdown
.selectAll('myOptions')
.data(data)
.enter()
.append('option')
.text(function (d) { return d.abbr; }) //text showed in the options
.attr("value", function (d) { return d.code; }) //values returned by each option
The problem is that repeated values are shown instead of only one for each code/abbr as you can see below:
<select id="sel">
<option value="1">BR</option>
<option value="1">BR</option>
<option value="43">RS</option>
<option value="31">MG</option>
<option value="31">MG</option>
<option value="35">SP</option>
<option value="42">SC</option>
<option value="1">BR</option>
<option value="26">PE</option>
</select>
How can I filter the data to have only unique values in the options instead?
<select id="sel">
<option value="1">BR</option>
<option value="43">RS</option>
<option value="31">MG</option>
<option value="35">SP</option>
<option value="42">SC</option>
<option value="26">PE</option>
</select>
== EDIT ==
I was able to get uniques using set just like the following:
const selectedData = [... new Set(data.map(d => d.abbr))].sort();
But then I can work only with abbr. How could I get code too?
Tried [... new Set(data.map(d => [d.abbr, d.code))], but without success, as this creates an object of arrays with all unfiltered data again.