I have data that is an array of objects loaded from csv. I would like to filter out the undesirable values and sort the remaining values and put them in another array for me to load a "select" element in javascript.
0: Object { type: "Feature", id: "AFG", female_lfpr: "48.65999985", … }
1: Object { type: "Feature", id: "AGO", female_lfpr: "75.41200256", … }
2: Object { type: "Feature", id: "ALB", female_lfpr: "47.19100189", … }
The "data.features" looks like above. I would like to remove countries where id is -99 or where country_name is "" or "undefined" and collect the valid country id and names in another array.
const valid_countries = {};
valid_countries = data.features.sort(function(a, b)
{
if ( (typeof a.country_name !== 'undefined') && (a.id !== '-99') &&(a.country_name !== ""))
{
valid_countries.id = a.id
valid_countries.country_name = a.country_name
// return a.country_name.localeCompare(b.country_name);
}
});
I need an array valid_countries that has an id as well as corresponding country name.
{id: AUS, name:Australia}
{id: USA, name:United States of America}
which can be used to populate a "select" options and values such that the country names are listed in alphabetical order.
d3.select('#country_dropdown')
.selectAll("option")
.data(valid_countries)
.enter()
.append("option")
.attr("value", function(c){ return c.id; })
.text(function(c) { return c.country_name; });
So your original array looks something like:
const data = [{ type: "Feature", id: "AFG", female_lfpr: "48.65999985", country_name: "Afghanistan" }, { type: "Feature", id: "AGO", female_lfpr: "75.41200256" }, { type: "Feature", id: "ALB", female_lfpr: "47.19100189", country_name: "Albania" }];
You can filter out the invalids with something like
const filtered = data.filter(element => { return (element.country_name != null && element.country_name !== '-99')})
Above the != null
checks for 0-length string and undefined
.
And then sort with
const sorted = filtered.sort((a, b) => { return /* your comparison here*/ });
If you need to transform the result to format of { id: 'id', name: 'name'}
, this can be achieved by calling
const result = sorted.map(item => { id: item.id, name: item.country_name });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.