城市及其国家的结构如下:
let data = [
{
country: 'Serbia',
city: 'Belgrad',
},
{
country: 'Ukraine',
city: 'Kiev',
},
{
country: 'Russia',
city: 'Moscow',
},
{
country: 'Russia',
city: 'Sant-Peterborough',
},
{
country: 'Ukraine',
city: 'Lvov',
},
{
country: 'China',
city: 'Beijing',
},
{
country: 'Poland',
city: 'Cracow',
},
];
我的解决方案是:
let arr =[];
let sum= 0;
for ( elem of data){
arr.push(elem.country)
}
let uniqueCountries = [...new Set(arr)];
console.log(uniqueCountries.length)
有用。
我的问题:
是否有可能找到更好的解决方案(例如不使用新的Set)?
最佳答案
Set具有可以使用的size属性。
您还可以通过在集合实例化中使用map来简化代码,如下所示:
let data = [
{ country: "Serbia", city: "Belgrad" },
{ country: "Ukraine", city: "Kiev" },
{ country: "Russia", city: "Moscow" },
{ country: "Russia", city: "Sant-Peterborough" },
{ country: "Ukraine", city: "Lvov" },
{ country: "China", city: "Beijing" },
{ country: "Poland", city: "Cracow" }
]
const set = new Set(data.map(o => o.country))
console.log(set.size)
我不确定为什么不在这里使用集合,但是如果您愿意,可以使用地图代替:
let data = [
{ country: "Serbia", city: "Belgrad" },
{ country: "Ukraine", city: "Kiev" },
{ country: "Russia", city: "Moscow" },
{ country: "Russia", city: "Sant-Peterborough" },
{ country: "Ukraine", city: "Lvov" },
{ country: "China", city: "Beijing" },
{ country: "Poland", city: "Cracow" }
];
const map = data.reduce((a, o) => (a[o.country] = 0, a), {})
console.log(Object.keys(map).length)