جافا سكريبت - إزالة العناصر المكررة من مصفوفة من الكائنات في تايب سكريبت
لذلك وجدت واجهة برمجة تطبيقات (API) التي أقوم من خلالها بجلب جميع الدول ومدنها الخاصة. هذه هي واجهة برمجة التطبيقات: https://documenter.getpostman.com/view/1134062/T1LJjU52#4829d16f-0f4e-43ec-886e-68ebad1221d8
أنا أحصل على نسخ مكررة من المدن من الاستجابة، والتي قمت بالتحقق منها في Postman، كما هو موضح أدناه:
{
"country": "United States",
"cities": [
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbotsford",
],
},
أحتاج إلى إزالة التكرارات، وقد تمكنت من جعلها تعمل، لكنها ليست جميلة جدًا... هذه هي دالتي لتنسيق الكود:
getCountries = async () => {
if(!this.mounted) return;
interface typeData {
data: Array<{country: string, cities: Array<string>}>;
error: boolean;
msg: string;
}
const result: typeData = await this.data.GetCountries();
let findDuplicates = result.data.map(i => {
let currentCountry = i.country;
let currentCities: Array<string> = [];
i.cities.filter(c => {
if(!currentCities.includes(c)) currentCities.push(c);
});
let finalArray: Array<{country: string, cities: Array<string>}> = [{
country: currentCountry,
cities: currentCities
}];
return finalArray;
}).reduce((sofar, current) => [...sofar, ...current], []);
findDuplicates && this.setState({data: {weather: this.state.data?.weather, countries: findDuplicates}})
}
هذا يبدو وكأنه طريقة غير فعّالة للقيام بذلك، هل هناك أي طريقة يمكنني من خلالها القيام بهذا في سطر واحد من الكود، باستخدام reduce أو map أو filter؟
لقد وجدت أمثلة مشابهة هنا، لكن لا شيء منها له هذا الهيكل:
Array<{country: string, cities: Array<string>}>.
الإجابة رقم 1
يمكنك تقليل التكرارات باستخدام Set:
let response = {
"country": "United States",
"cities": [
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbotsford",
],
};
response.cities = [...new Set(response.cities)];
console.log(response.cities);
الإجابة رقم 2
سؤال مشابه: إزالة القيم المكررة من مصفوفة JS
أو يمكنك تجربة هذا
let data={
"country": "United States",
"cities": [
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbeville",
"Abbotsford",
],
}
let obj={}
data.cities.forEach((x)=>obj[x]=x)
let newArr=Object.keys(obj)
console.log(newArr)