【发布时间】:2022-01-20 12:11:38
【问题描述】:
我有一个我称之为fareZone 对象的数组。每个票价区对象都有一个 stops 数组。
我希望保留stop 对象的第一次出现,并从数组中删除同一对象的所有其他出现(同样意味着它具有相同的atcoCode)。
对象数组
const fareZones = [{
name: 'Zone 1',
stops: [{
stopName: 'Ashton Bus Station',
atcoCode: '1800EHQ0081',
},
{
stopName: 'New Street',
atcoCode: '1800EHQ0721',
},
{
stopName: 'Farfield Road',
atcoCode: '1800EHQ0722',
},
{
stopName: 'Ashton Bus Station',
atcoCode: '1800EHQ0081',
},
{
stopName: 'New Street',
atcoCode: '1800EHQ0041',
},
],
prices: [],
},
{
name: 'Zone 2',
stops: [{
stopName: 'Henrietta Street',
atcoCode: '1800EH24201',
}, ],
prices: [],
},
{
name: 'Zone 3',
stops: [{
stopName: 'Crickets Ln',
atcoCode: '1800EH24151',
},
{
stopName: 'Tameside College',
atcoCode: '1800EH21241',
},
{
stopName: 'Ashton Bus Station',
atcoCode: '1800EHQ0081',
},
],
prices: [],
}]
期望的结果
const fareZones = [{
name: 'Zone 1',
stops: [{
stopName: 'Ashton Bus Station',
atcoCode: '1800EHQ0081',
},
{
stopName: 'New Street',
atcoCode: '1800EHQ0721',
},
{
stopName: 'Farfield Road',
atcoCode: '1800EHQ0722',
},
{
stopName: 'New Street',
atcoCode: '1800EHQ0041',
},
],
prices: [],
},
{
name: 'Zone 2',
stops: [{
stopName: 'Henrietta Street',
atcoCode: '1800EH24201',
}, ],
prices: [],
},
{
name: 'Zone 3',
stops: [{
stopName: 'Crickets Ln',
atcoCode: '1800EH24151',
},
{
stopName: 'Tameside College',
atcoCode: '1800EH21241',
},
{
stopName: 'Ashton Bus Station',
atcoCode: '1800EHQ0081',
},
],
prices: [],
}]
注意 Zone 1 中的第三站是如何被删除的,因为它是重复的。
如何在 JavaScript 中实现这一点?
当前进度
// for each fare stage, check to see if we have duplicate stops
fareZones.map((fz) => {
let stopsWithinFareZone = fz.stops;
const atcoCodesOfStopsWithinFareZone = stopsWithinFareZone.map((s) => s.atcoCode);
const hasDuplicateStops = hasDuplicates(atcoCodesOfStopsWithinFareZone);
if (hasDuplicateStops) {
// so we have duplicates, how do I keep the first occurrence
// and remove all other occurrences of the duplicate stop
}
});
export const hasDuplicates = (array: string[]): boolean => {
return new Set(array).size !== array.length;
};
【问题讨论】:
标签: javascript arrays filter