My array consists of what I call fareZone
objects. Each fare zone object includes an array of stops
.
I am looking to retain the first instance of a stop
object and eliminate all other occurrences of the same object (meaning it has the same atcoCode
) from the array.
Fare Zone Array
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: [],
}]
Desired Result
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: [],
}]
Observe how the third stop in Zone 1 was erased because it was a duplicate.
How would I accomplish this task using JavaScript?
Current Progress
// for each fare stage, check 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 can I keep the first instance
// and remove all other instances of the duplicate stop
}
});
export const hasDuplicates = (array: string[]): boolean => {
return new Set(array).size !== array.length;
};